简体   繁体   中英

Print JSON with “pretty” (indented) format

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"
}

TJSONObject does not support pretty printing.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM