Accessing Child Elements Of JSON Objects And Arrays
JSON Objects
We can access child elements of a TJSONValue object by using square brackets syntax with a path:
Object[‘path.to.a.value’]
Or a sequence of square brackets with paths, because each [] call simply returns another TJSONValue:
Object[‘path’][‘to’][‘a’][‘value’]
Dots in the path allow to get access to child elements. For arrays square brackets with indices can be used:
Object[‘subobject.subarray[2].key’]
The result of the square brackets operator is a TJSONValue object, so it must be tested for a specific type before accessing its values.
The result of the square brackets operator is nil, if the specified path does not exist in the object.
var obj: TJSONObject;begin obj := TJSONValue.Parse(‘{“boolValue”: true}’) as TJSONObject; if obj[‘boolValue’].IsBoolean then begin if obj[‘boolValue’].AsBoolean then LogInfo(‘The boolean value is true’) else LogInfo(‘The boolean value is false); end; obj.Free;end;The following list of TJSONValue methods can be used to cast its value into one of the types:
AsString – returns a standard string value (not a TJSONString object)
AsInt – returns a standard integer value (not a TJSONNumber object)
AsInt64 – returns a standard int64 value (not a TJSONNumber object)
AsNumber – returns a standard double value (not a TJSONNumber object)
AsBoolean – returns a standard boolean value (not a TJSONBool object)
AsObject – returns a TJSONObject object (we used it for downcasting in our samples)
AsArray – returns a TJSONArray object
These methods may throw an error if the casting or conversion can not be done due to a type mismatch. If you are not sure what the type of the value is, use one of the methods described in “JSON Variable Types” first.
JSON Arrays
If you have a TJSONArray object, you can access its elements by an integer index using square brackets syntax:
LogInfo(Array[0].AsString);
Remember: Elements of a JSON array are zero indexed. So they can be accessed by the following indices:
[0 … Count – 1]
You can also obtain a number of children of a JSON array using Count method and iterate through the elements as in the example:
var arr: TJSONArray; i: integer;begin arr := TJSONValue.Parse('["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]') as TJSONArray; for i := 0 to arr.Count - 1 do LogInfo(arr[i].AsString); arr.Free;end;Output
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday