JSON Parse

In the example i have a JSON and i am accessing all the element and values.
It works fine and i don't have any problem.
I would like to know if there is a better way of getting elements and values.
I mean properties and methods not logic.

TestJSON.zip (23.0 KB)

Thank you :slight_smile:

1 Like

Hi George

I prefer more Delphi style something like this:

type
  TMyDataValue = record
    ID: Integer;
    DESCRIPTION: string;
  end;

  TMyJsonDataArray = record
    TableName: string;
    Values: Array of TMyDataValue;
  end;

  TMyJsonData = record
    ERRORS: string;
    WARNINGS: string;
    MESSAGES: string;
    DATA: Array of TMyJsonDataArray;
  end;

procedure TForm1.ParseMyJSON2;
var
  txt: string;
  JS: JSValue;
  MyJsonData: TMyJsonData;
  I,J: Integer;
begin
  WebMemo2.Lines.Clear;
  asm
    debugger;
  end;
  txt := WebMemo1.Lines.Text;
  asm
    JS = JSON.parse(txt);
  end;
  MyJsonData := TMyJsonData(JS);
  if isDefined(MyJsonData.ERRORS) then
    WebMemo2.Lines.Add('Has "ERRORS" with value "'+ MyJsonData.ERRORS + '"');

  if isDefined(MyJsonData.WARNINGS) then
    WebMemo2.Lines.Add('Has "WARNINGS" with value "'+ MyJsonData.WARNINGS + '"');

  if isDefined(MyJsonData.MESSAGES) then
    WebMemo2.Lines.Add('Has "MESSAGES" with value "'+ MyJsonData.MESSAGES + '"');

  if isDefined(MyJsonData.DATA) then
  begin
    for I := 0 to Length(MyJsonData.DATA) -1 do
    begin
      if isDefined(MyJsonData.DATA[I].TableName) then
        WebMemo2.Lines.Add('Has "TableName" with value "'+MyJsonData.DATA[I].TableName+'"');
      for J := 0 to Length(MyJsonData.DATA[I].Values) -1 do
      begin
        WebMemo2.Lines.Add(MyJsonData.DATA[I].Values[J].ID.ToString + ': ' + MyJsonData.DATA[I].Values[J].DESCRIPTION);
      end;
    end;
  end;
end;

Just stay with the "native" TJSObject/TJSArray. Only use the Delphi JSON implementation for compatibility reasons with existing VCL Delphi code. In addition, I experienced a lot of problems with the JSON Delphi implementation of which I don't know if they were ever fixed. Search this forum on this topic.

I agree. I mean by "Delphi style" is to use record structures where possible to code easier.

Thank you both :slight_smile:

@Mehmet_Emin_Borbor I prefer the record style you suggest and I will use it.
The code is much easier and cleaner as you said.

Can you explain to me the
asm
debugger;
end;
why you use it and what does it do?

I just put a javascript breakpoint to stop at the location so that you can inspect the code within Chrome console to see how this pascal code behaves under JS environment. I recommend looking into the js file code.

Other than that just remove that part.

1 Like