Andrey Andrey - 1 year ago 378
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).

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:

"header":"JSON viewer",
"label":"Nice tree format"

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"
Json : ISuperObject;
Json := TSuperObject.ParseString(PWideChar(InString), True);
Result := Json.AsJson(true, false); //Here comes your result: pretty-print JSON

Answer Source

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); ]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download