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, orjeFileErrorafterLoad); queries report nothing (SelectNodesreturns an empty list, so aFor Eachover it does not run;SelectSingleNodeandRootreturnNothing;ExistsreturnsFalse), and getters with a default return the default. ParseError.FilePosis the 0-based character position in the whole text;LineandLinePosare 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
Loadis reported inParseErroras well;SaveraisesjeFileError.
Related topics
en/wiki/msaccess/json/how-to/handle-invalid-json.txt · Zadnja sprememba: uporabnika Wolfgang van der Stille