Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 243
Andrey Prokhorov Avatar asked Aug 29 '13 12:08

Andrey Prokhorov


2 Answers

If you do not want to use any external library, and you're using a delphi XE5 or newer, there is a very handy TJson.Format() function in the REST.Json unit.

uses json, REST.Json;

{ ... }    

function FormatJSON(json: String): String;
var
  tmpJson: TJsonObject;
begin
  tmpJson := TJSONObject.ParseJSONValue(json);
  Result := TJson.Format(tmpJson);

  FreeAndNil(tmpJson);
end;
like image 150
Bob Avatar answered Sep 20 '22 05:09

Bob


This is a bit old, but if anyone is interested Delphi's native System.JSON unit can do this too. Sample uses a TMemo and a TButton to format the JSON

procedure TForm1.btnFormatJSONClick(Sender: TObject);
const
 DEF_INDENT = 2;
var
 JO : TJSONObject;
begin
 try
  JO := TJSONObject.ParseJSONValue(memoJSON.Text) as TJSONObject;
  memoJSON.Text := JO.Format(DEF_INDENT);
 except
  on E:Exception do
   begin
    MessageDlg('Error in JSON syntax', mtError, [mbOK], 0);
   end;
 end;
end;
like image 35
Rick Zarr Avatar answered Sep 19 '22 05:09

Rick Zarr