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?
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: