How do I pretty-print JSON in Delphi?

前端 未结 5 785
盖世英雄少女心
盖世英雄少女心 2020-12-31 19:22

I am looking for a function that will take a string of JSON as input and format it with line breaks and indentations (tabs).

Example: I have input line:



        
5条回答
  •  一向
    一向 (楼主)
    2020-12-31 20:00

    This is a bit old, but if anyone is interested Delphi's native System.JSON unit can do this too. Sample uses a TMemo and a TButton to format the JSON

    procedure TForm1.btnFormatJSONClick(Sender: TObject);
    const
     DEF_INDENT = 2;
    var
     JO : TJSONObject;
    begin
     try
      JO := TJSONObject.ParseJSONValue(memoJSON.Text) as TJSONObject;
      memoJSON.Text := JO.Format(DEF_INDENT);
     except
      on E:Exception do
       begin
        MessageDlg('Error in JSON syntax', mtError, [mbOK], 0);
       end;
     end;
    end;
    

提交回复
热议问题