Andrey Andrey - 5 months ago 99
JSON Question

How do I pretty-print JSON in Delphi?

I am looking for a function that will take a string of JSON as input and format it with line breaks and indentations (tabs).

Example:
I have input line:

{"menu": {"header": "JSON viewer", "items": [{"id": "Delphi"},{"id": "Pascal", "label": "Nice tree format"}, null]}}


And want to get a readable result as text:

{
"menu":{
"header":"JSON viewer",
"items":[
{
"id":"Delphi"
},
{
"id":"Pascal",
"label":"Nice tree format"
},
null
]
}
}


I found a lot of examples for PHP and C#, but not for Delphi.
Could someone help with such a function?

Update - Solution with SuperObject:

function FormatJson (InString: WideString): string; // Input string is "InString"
var
Json : ISuperObject;
begin
Json := TSuperObject.ParseString(PWideChar(InString), True);
Result := Json.AsJson(true, false); //Here comes your result: pretty-print JSON
end;

Answer

Use the superobject library, make sure that you use the latest version from the repository file, not the 1.2.4 ZIP.

Then you can format your TSuperObject object with .AsJSON(true) (the 'true' does the trick).

[ Note that you have no control over the order in which the JSON fields are displayed ]

[ And to create your object from the string: var lJSON : ISuperObject; lJSON := SO(string); ]