B4J Code Snippet May Be JSON (MayBeJSON)

B4X implementation of the "mayBeJSON" method from JSON Lib - https://github.com/jenkinsci/json-lib

The method tests if the input String possibly represents a valid JSON String. This is handy as a check before running the JSONParser.

B4X:
Sub MayBeJSON(Input As String) As Boolean
    If Input.Length = 0 Then Return False
    If Input = Null Then Return False
    If Input.ToLowerCase = "null" Then Return False
    If Input.StartsWith("{") And Input.EndsWith("}") Then Return True
    If Input.StartsWith("[") And Input.EndsWith("]") Then Return True   
    Return False   
End Sub
 
[CODE lang="b4x" title="Update"]#if B4R
Sub MayBeJSON (Input() As Byte) As Boolean
Dim bc As ByteConverter
If Input.Length = 0 Then
Return False
End If
If bc.StartsWith(Input, "{".GetBytes) And bc.EndsWith(Input, "}".GetBytes) Then Return True
If bc.StartsWith(Input, "[".GetBytes) And bc.EndsWith(Input, "]".GetBytes) Then Return True
Return False
End Sub
#Else
Sub MayBeJSON(Input As String) As Boolean
If Input.Length = 0 Then Return False
If Input = Null Then Return False
If Input.ToLowerCase = "null" Then Return False
If Input.StartsWith("{") And Input.EndsWith("}") Then Return True
If Input.StartsWith("[") And Input.EndsWith("]") Then Return True
Return False
End Sub
#end if[/CODE]
 
Last edited:
I had this problem recently and decided on the brute force approach. Put the parser in a try ... catch block. If it succeeds, then it's valid otherwise not. I'm sure there are still some situations that will slip through.
 
Note i'm updating for B4R...
Where MCU also can hang, and no another "try" to re-try :)
 
Back
Top