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?

1
  • 1
    Json.Format() - string with beautifier; Json.ToString() - string without beautifier; Json.ToJson() - string without beautifier and with escaping special symbols Commented Jul 17, 2023 at 8:05

1 Answer 1

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


Sign up to request clarification or add additional context in comments.

5 Comments

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 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
@DavidHeffernan Control characters like CR are not allowed inside quotes, so removing linebreaks and spaces around it (speak: around the linebreak) is no problem.
@AmigoJack You'd probably also want to remove other spaces though, not just around line breaks
@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 "😐".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.