Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONValue to Indented String

In Delphi XE2, I need to make a function that receives a JSONValue and returns an indented String, much like JSONLint. This JSONValue could be any type of JSON, could be an array, an object, even just a string, so I have to make sure to cover all types with this function. I have no idea where to start.

like image 483
bpromas Avatar asked Jun 30 '26 00:06

bpromas


1 Answers

You'll have to do it recursively. Something like this:

const INDENT_SIZE = 2;

procedure PrettyPrintJSON(value: TJSONValue; output: TStrings; indent: integer = 0); forward;

procedure PrettyPrintPair(value: TJSONPair; output: TStrings; last: boolean; indent: integer);
const TEMPLATE = '%s : %s';
var
  line: string;
  newList: TStringList;
begin
  newList := TStringList.Create;
  try
    PrettyPrintJSON(value.JsonValue, newList, indent);
    line := format(TEMPLATE, [value.JsonString.ToString, Trim(newList.Text)]);
  finally
    newList.Free;
  end;

  line := StringOfChar(' ', indent * INDENT_SIZE) + line;
  if not last then
    line := line + ','
  output.add(line);
end;

procedure PrettyPrintJSON(value: TJSONValue; output: TStrings; indent: integer);
var
  i: integer;
begin
  if value is TJSONObject then
  begin
    output.add(StringOfChar(' ', indent * INDENT_SIZE) + '{');
    for i := 0 to TJSONObject(value).size - 1 do
      PrettyPrintPair(TJSONObject(value).Get(i), output, i = TJSONObject(value).size - 1, indent + 1);
    output.add(StringOfChar(' ', indent * INDENT_SIZE) + '}');
  end
  else if value is TJSONArray then
    //left as an exercise to the reader
  else output.add(StringOfChar(' ', indent * INDENT_SIZE) + value.ToString);
end;

This covers the basic principle. WARNING: I wrote this up off the top of my head. It may not be correct or even compile, but it's the general idea. Also, you'll have to come up with your own implementation of printing a JSON array. But this should get you started.

like image 101
Mason Wheeler Avatar answered Jul 01 '26 21:07

Mason Wheeler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!