3

If I create a JSON object and print it on the console:

LJSONObject:= TJSONObject.Create;
LJSONObject.AddPair(TJSONPair.Create(TJSONString.Create('Hello'), TJSONString.Create('World')));
LJSONObject.AddPair(TJSONPair.Create(TJSONString.Create('Ciao'), TJSONString.Create('Mondo')));
Writeln(LJSONObject.ToString);

the result is:

{"Hello":"World", "Ciao":"Mondo"}

How I can print the result with nicer indentation, like this?

{
   "Hello":"World",
   "Ciao":"MOndo"
}
David
  • 13,360
  • 7
  • 66
  • 130
padibro
  • 1,324
  • 10
  • 56
  • 95
  • There's no support of `TJSONObject` for pretty print at this time. But with `PrettyPrintJSON` function from [`this question`](http://stackoverflow.com/q/11797583/960757) you can write something [`like this`](http://pastebin.com/QgkYffN3). – TLama Jul 10 '14 at 10:07
  • It's not "correct" indentation - indentation doesn't matter for a JSON parser. It's useful for humans reading it though. That makes it "pretty printing" as @David Heffernan calls it in his answer below, or something similar. – David Jul 10 '14 at 10:07
  • You can also use online tools like http://jsonprettyprint.net if you don't mind copying pasting. – Javaaaa Nov 19 '14 at 17:04

2 Answers2

5

TJSONObject does not support pretty printing.

Other JSON libraries do. For instance SuperObject, as discussed here: How do I pretty-print JSON in Delphi?

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

As Sir Rufo pointed out, there is an inbuilt option as of XE5.

uses REST.JSON,System.JSON;
...
function PrettyJSON(jsonstring:String):String;
    var jdoc:TJSONObject;
begin
    jdoc:=TJSONObject.ParseJSONValue(jsonstring) as TJSONObject;
    result:=TJSON.Format(jdoc)
end;
Robbie Matthews
  • 1,404
  • 14
  • 22