Android Code Snippet Check if a string is valid Json (isJson)

Discussion in 'Code Snippets' started by Douglas Farias, Dec 2, 2018.

  1. Douglas Farias

    Douglas Farias Expert Licensed User

    Hi
    Like isBase64 posted here
    https://www.b4x.com/android/forum/threads/check-if-a-string-is-base64-isbase64.98444/

    here is the isJson function based on JSON documentation
    Code:
    Sub is_Json(json As StringAs Boolean
        
    If Regex.IsMatch($"[{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}"$, json.Trim) And json.Length > 2  Then
            
    Return True
        
    Else
            
    Return False
        
    End If
    End Sub

    example of use
    Code:
    Log(is_Json($"{"success":false,"msg":"teste!"}"$))
        
    Log(is_Json($"{"success":false,"msg":"$))
    The result log is
    true
    false


    Credits: stackoverflow, Douglas Farias and JSON documentation
     
    Last edited: Dec 2, 2018
  2. Erel

    Erel Administrator Staff Member Licensed User

    This code is not enough to say whether it is a valid json string or not. I don't see any reason for this test.

    If you think that the code might not be valid then catch the error:
    Code:
    Try
     
    Dim jp As JsonParser
     ..
    Catch
     
    'string input is not valid
    End Try
     
    Multiverse app and karld like this.
  3. Douglas Farias

    Douglas Farias Expert Licensed User

    2 options here.

    Code:
    Dim j As HttpJob
    j.Initialize(
    "", Me)
    j.Download(
    "https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
      
    if is_Json(j.GetString) then
            
    'PARSE HERE
      End If
    End If
    j.Release
    OR

    Code:
    Dim j As HttpJob
    j.Initialize(
    "", Me)
    j.Download(
    "https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        
    Try
            
    Dim jp As JSONParser
            jp.Initialize(j.GetString)
        
    Catch
            
    Log(LastException)
        
    End Try
    End If
    j.Release

    I particularly prefer the if, but here is the 2 options, more options the better.
     
  4. woniol

    woniol Active Member Licensed User

    Hi,
    Code:
    Try
            
    Dim jp As JSONParser
            jp.Initialize(j.GetString)
        
    Catch
            
    Log(LastException)
        
    End Try
    is not enough. It will not raise an error even in string is not valid json.
    no need to call JSONParser method:
    Code:
    Dim jp As JSONParser
    jp.Initialize(j.GetString)
    jp.NextObject
    for the error to be catched
     
    peacemaker likes this.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice