Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions modules/brl/cerberusdoc/json.cerberusdoc
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Function Main:Int()
For Local jn := Eachin JsonObject( json ).GetData()
Print "node "+ jn.Key() +" containing "+ jn.Value().ToJson()
End
Print JsonObject( json ).ToPrettyJson()
' JsonArray
Case JsonValue.ARRAYTYPE
For Local entry := Eachin JsonArray( json ).GetData()
Expand Down Expand Up @@ -143,6 +144,12 @@ Otherwise, it throws a [[JsonError]].

Converts value to a JSON string.

# Method ToPrettyJson:String( tab2spaces:Bool=False,tabsize:Int=4 )

Generates a formatted Json string.~n
The default indent tabulation character is set to the ASCII charater for horizontal tabs (code 0x09). You can change this by setting to use the space character (ASCII code 0x20) by passing *`True`* for @tab2spaces parameter, and the number of space characters to use in the @tabsize parameter.~n
The method is most useful when used with [[JsonObject]] when generating a Json string for outputing to a file.


# Class JsonObject Extends JsonValue

Expand Down
59 changes: 59 additions & 0 deletions modules/brl/json.cxs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,65 @@ Class JsonValue Abstract
' implement a proper ToJson OR a proper PushJson.
' Nodes that can contain childs (Object and Array) implement PushJson
' Nodes that only have value (Null, Bool, Number, String) implement ToJson

' Outputs a pretty formatted jason string.
Method ToPrettyJson:String( tab2spaces:Bool=False,tabsize:Int=4 )
Local result:String = "", indent:Int = 0, inString:Bool = False, prev:="",
json:=Self.ToJson(), tabs:=""

If tab2spaces
For Local i:=0 Until tabsize
tabs+=" "
Next
Else
tabs="~t"
Endif

For Local i:Int = 0 Until json.Length
Local c:= String.FromChar( json[i] )

' detect string start/end
If c = "~q" And prev <> "\" Then
inString = Not inString
Endif

If Not inString
Select c
Case "{","["
result += c + "~n"
indent += 1
result += Indent( indent,tabs )
Case "}","]"
result += "~n"
indent -= 1
result += Indent( indent,tabs ) + c
Case ","
result += c + "~n" + Indent( indent,tabs )
Case ":"
result += ": "
Default
If Not (c=" " Or c="~t")
result += c
Endif
End Select
Else
result += c
Endif

prev = c
Next

Return result
End

Method Indent:String( level:Int,tabs:String )
Local s:String = ""
For Local i:Int = 0 Until level
s += tabs
Next
Return s
End

End

' object - can contain 'string : value' pairs
Expand Down