Android Code Snippet PyJSON

Discussion in 'Code Snippets' started by wonder, Jun 11, 2019.

  1. wonder

    wonder Expert Licensed User

    Here's a treat for my Pythonic friends who got used to its JSON module! :)

    Based on: https://docs.python.org/3/library/json.html

    B4X Code Module:
    Code:
    Private Sub Process_Globals
        
    Public  Indent = 4 As Int
        
    Private gen As JSONGenerator
        
    Private par As JSONParser
    End Sub

    Public Sub LoadS(data As StringAs Object
        
    Dim obj As Object 
        
    Do While True
            
    Try
                par.Initialize(data)
                obj = par.NextArray
                
    Exit
            
    Catch
                Pass
            
    End Try
            
    Try
                par.Initialize(data)
                obj = par.NextObject
                
    Exit
            
    Catch
                Pass
            
    End Try
            
    Try
                par.Initialize(data)
                obj = par.NextValue
                
    Exit
            
    Catch
                LogError(
    LastException)
            
    End Try
            
    Exit
        
    Loop
        
    Return obj
    End Sub

    Public Sub DumpS(obj As Object) As String
        
    If obj Is Map Then
            gen.Initialize(obj)
            
    Return gen.ToPrettyString(Indent)
        
    Else If obj Is List Then
            gen.Initialize2(obj)
            
    Return gen.ToPrettyString(Indent)
        
    End If
        
    Return obj
    End Sub

    Public Sub Dump(obj As Object, filedir As String, filename As String)
        
    File.WriteString(filedir, filename, DumpS(obj))
    End Sub

    Public Sub Load(filedir As String, filename As StringAs Object
        
    Return LoadS(File.ReadString(filedir, filename))
    End Sub

    Public Sub Pretty(data As StringAs String
        
    Return DumpS(LoadS(data))
    End Sub

    Private Sub Pass As Boolean
        
    Return True
    End Sub
    Usage:
    Code:
    'Module name: Json.bas

    Json.Indent = 
    2 'Optional - default: 4
    Dim obj = Json.Load(File.DirApp, "data.json"As Object
    Log(Json.DumpS(obj))
     
    DavideV and inakigarm like 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