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:
Usage:
Based on: https://docs.python.org/3/library/json.html
B4X Code Module:
B4X:
Private Sub Process_Globals
Public Indent = 4 As Int
Private gen As JSONGenerator
Private par As JSONParser
End Sub
Public Sub LoadS(data As String) As 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 String) As Object
Return LoadS(File.ReadString(filedir, filename))
End Sub
Public Sub Pretty(data As String) As String
Return DumpS(LoadS(data))
End Sub
Private Sub Pass As Boolean
Return True
End Sub
Usage:
B4X:
'Module name: Json.bas
Json.Indent = 2 'Optional - default: 4
Dim obj = Json.Load(File.DirApp, "data.json") As Object
Log(Json.DumpS(obj))