Farbschema: Dunkel
Sie befinden sich hier: start » en » Documentation » Microsoft Access development tools » WKL Office JSON » WKL Office JSON how-to guides » How to: Handle invalid JSON

How to: Handle invalid JSON

React to JSON that cannot be parsed, and tell the user or the log where the problem is.

Solution overview

LoadJson and Load return False for invalid input and fill ParseError with the error code, the line and column, the text of the line and the reason, as loadXML does in MSXML. No VBA error is raised at load time.

Implementation

Dim doc As New JDoc
If Not doc.LoadJson(text) Then
    With doc.ParseError
        Debug.Print "Line " & .Line & ", column " & .LinePos & ": " & .Reason
        Debug.Print .SrcText
        If .LinePos > 0 Then Debug.Print String(.LinePos - 1, " ") & "^"
    End With
    Exit Sub
End If

For a file:

If Not doc.Load(CurrentProject.Path & "\settings.json") Then
    MsgBox doc.ParseError.Reason, vbExclamation
End If

Remarks

  • Always check the return value. After a failed load only the getters without a default raise the error of the load again (jeParseError, or jeFileError after Load); queries report nothing (SelectNodes returns an empty list, so a For Each over it does not run; SelectSingleNode and Root return Nothing; Exists returns False), and getters with a default return the default.
  • ParseError.FilePos is the 0-based character position in the whole text; Line and LinePos are 1-based.
  • Comments, trailing commas and single quotes are invalid JSON; the reason names the unexpected character, the comma or the quotation marks (troubleshooting).
  • A missing or unreadable file for Load is reported in ParseError as well; Save raises jeFileError.
en/wiki/msaccess/json/how-to/handle-invalid-json.txt · Zuletzt geändert: von Wolfgang van der Stille