From e32a64827e498baead3544fec37c87ca3999dc18 Mon Sep 17 00:00:00 2001 From: jackdaw Date: Sun, 8 Mar 2026 20:26:31 +0000 Subject: [PATCH] Added a prettifier to output a formatted Json string. --- modules/brl/cerberusdoc/json.cerberusdoc | 7 +++ modules/brl/json.cxs | 59 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/modules/brl/cerberusdoc/json.cerberusdoc b/modules/brl/cerberusdoc/json.cerberusdoc index f1a7a16c..85bd35ff 100644 --- a/modules/brl/cerberusdoc/json.cerberusdoc +++ b/modules/brl/cerberusdoc/json.cerberusdoc @@ -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() @@ -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 diff --git a/modules/brl/json.cxs b/modules/brl/json.cxs index b9eec42e..73052bcf 100644 --- a/modules/brl/json.cxs +++ b/modules/brl/json.cxs @@ -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