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;
                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;
                        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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With