How do I parse nested JSON?

98 views Asked by At

How do I parse this JSON?

 

{
  "result": [
    {
      "animals": [
        {
          "id": 1,
          "name": "pig",
        }
      ]
    }
  ]
} 

I have tried to parse the JSON by:

jsonobject := TJsonObject.ParseJSONValue(RestResponse.Content) as TJsonObject;

Then I get "animals":[{"id" ... . Now here it gets complicated, how do I parse further to get id and name? Parse JSON further or parse JSON array? Can someone help me (with example code), please?

1

There are 1 answers

4
fpiette On

Your JSON string contain an array embedded in another array. You can get the value of the first array ("result") and iterate its elements. For each element you have an array of "animals" that you can iterate to get "id" and "name".

Simple code to do that :

const
    JSONStr2 =
'{' +
   '"result": [' +
     '{' +
       '"animals": [' +
         '{"id": 1, "name": "pig"},' +
         '{"id": 2, "name": "rabit"}' +
       ']' +
     '}' +
   ']' +
 '}';

 procedure TForm1.ButtonClick(Sender: TObject);
var
    JSONValue      : TJSONValue;
    JSONResult     : TJSONArray;
    JSONResultItem : TJSONValue;
    JSONAnimals    : TJSONArray;
    JSONAnimalItem : TJSONValue;
begin
    JSONValue := TJSONObject.ParseJSONValue(JSONStr);
    if not Assigned(JSONValue) then begin
        ShowMessage('JSON syntax error');
        Exit;
    end;
    try
        JSONResult := JSONValue.GetValue<TJSONArray>('result');
        for JSONResultItem in JSONResult do begin
            JSonAnimals := JSONResultItem.GetValue<TJSONArray>('animals');
            for JSONAnimalItem in JSONAnimals do begin
                Memo1.Lines.Add(Format('%s = %s',
                                       [JSONAnimalItem.GetValue<String>('id'),
                                        JSONAnimalItem.GetValue<String>('name')]));
            end;
        end;
    finally
        JSONValue.Free;
    end;
end;