0

Using the following code, I am able to format (beautify) JSON using the built-in Delphi functions from the System.JSON unit:

function FormatJson(json: String; IndentationCount: Cardinal): String;
begin
  try
    var JsonObject := TJSONObject.ParseJSONValue(json) as TJSONObject;
    Result := JsonObject.Format(IndentationCount);
  except
    on E:Exception do
    begin
      // Error in JSON syntax
    end;
  end;
end;

Is there a built-in function to do the opposite in Delphi? I want to minify my JSON.

If there isn't a built-in method, does anyone have a function written to minify JSON?

Shaun Roselt
  • 1,650
  • 5
  • 18
  • 44
  • 1
    Json.Format() - string with beautifier; Json.ToString() - string without beautifier; Json.ToJson() - string without beautifier and with escaping special symbols – Oleksandr Morozevych Jul 17 '23 at 08:05

1 Answers1

0

Yes, there is a built-in method to minify JSON using the System.JSON unit:

function MinifyJson(json: String): String;
begin
  var JsonObject := TJSONObject.ParseJSONValue(json) as TJSONObject;
  try
    Result := JsonObject.ToString;
  finally
    JsonObject.Free;
  end;
end;

And if you don't want to use a built-in method, you could simply Trim each line with the following function and this doesn't require System.JSON:

function MinifyJson(json: String): String;
begin
  for var I in json.Split([sLineBreak]) do
    Result := Result + I.Trim([' ', #09, #10, #13]);
end;

Here's a screenshot showing JSON minified in my UI using the above code:

Minify JSON


Shaun Roselt
  • 1,650
  • 5
  • 18
  • 44
  • The screenshot is so very unnecessary - you should textually quote your input and output. What's the point of needing to hand over a `String` instead of `TJSONObject` directly? Why not linking to the docs? Performance wise it would be smarter to just remove linebreaks and spaces around it from the input `String` instead of parsing everything. – AmigoJack Jul 16 '23 at 07:50
  • 1
    @AmigoJack you have to make sure you don't remove text inside quotes, so some minimal parsing is needed, at the very least. A tokeniser would probably allow you to do the job efficiently – David Heffernan Jul 16 '23 at 12:46
  • @DavidHeffernan [Control characters like CR are not allowed inside quotes](https://stackoverflow.com/a/16690186/4299358), so _removing linebreaks and spaces **around it**_ (speak: around the linebreak) is no problem. – AmigoJack Jul 17 '23 at 06:37
  • @AmigoJack You'd probably also want to remove other spaces though, not just around line breaks – David Heffernan Jul 17 '23 at 07:31
  • @DavidHeffernan Yes, point taken. Likewise the input is not guaranteed to always have linebreaks for each key/value pair or each bracket. But then again we could also talk about eliminating needless escapings like [`"\uD83D\uDE10"` down to `""`](https://en.wikipedia.org/wiki/JSON#Character_encoding). – AmigoJack Jul 17 '23 at 16:23