Formatting JSON in Delphi for maximum human readability

If you have ever wanted to format a json string in Delphi, one option is to use one of the available 3rd party JSON libraries. Starting with Delphi XE5, you can use a function called REST.Json.TJson.Format. Below I have included some sample code demonstrating the use of it. Make sure you add Rest.Json and System.Rest the the uses section on units that use this function.

program jsonformatter;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Rest.Json,
  System.Json;

var
  LJSONObject : TJSONObject;
  jsonString : String;
  resultStr : String;
begin
  try
    jsonString := '{"menu": { "id": "file", "value": "File", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"},{"value": "Close", "onclick": "CloseDoc()"}]}}}';
    LJSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(jsonString), 0) as TJSONObject;
    resultStr := REST.Json.TJson.Format(LJSONObject);
    writeln(resultStr);
    readln;
    { TODO -oUser -cConsole Main : Insert code here }
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.