Introduction to JSON Path Expressions
JavaScript Object Notation (JSON) is a lightweight text-based format used for interchanging data. It has two structures: an object and an array.
- An object contains key/value pairs: { “key” : “value” }.
For example:
In {“hello”:123}, the key is the string “hello” and the value is the number 123;
In {“hello”:null}, the key is the string "hello" and the value is null.
- An array is an ordered list of values: [ value1, value2 ].
The value can be an object, an array, a number, a string, or one of (false, null, true).
For example, in [ {“test1”:123} , {“test2”:234} ], there are two objects.
As an array can contain objects or arrays, an object can also contain objects or arrays.
Usually, an API will give an example of the return value, so you can see the returned data structure.
The return value of JSON Path is an array. Therefore, to query the needed data, you need to apply JSON Path to the resulting data item.
In JSON Path, the $ represents the root element, whether it is an object or array. You can index JSON data according to their type.
For an object, you can index the value by the key.
For example:
{"hello": 123},
you can index the value 123 based on the key:
$.hello or $[‘hello’]
Note that if the key is Chinese, it must be in the form of $[‘key’].
For an array, you must index data in order.
For example,
[ {“test1”:123} , {“test2”:234} ],
if you want to index the value of the first object in the array, then type $[0].test1; if you want to index the value of the second object in the array, then type $[1].test2.
Note that [0] indicates the first object, array, or value in the indexed array, and [1] indicates the second object, array, or value in the indexed array.
You can try some more complicated indexes:
{
"address" : "12461 S Mainstreet, Etiwanda, CA 91739, United States",
"config_str" : "{\\\"side\\\":\\\"face\\\"}",
"face_rect":{
"angle": -90,
"center":{
"x" : 952,
"y" : 325.5
},
"size":{
"height":181.99,
"width":164.99
}
},
"card_region":[
{"x":165,"y":657},
{"x":534,"y":658},
{"x":535,"y":31},
{"x":165,"y":30}
],
"face_rect_vertices":[
{
"x":1024.6600341796875,
"y":336.629638671875
},
{
"x":906.66107177734375,
"y":336.14801025390625
},
{
"x":907.1590576171875,
"y":214.1490478515625
},
{
"x":1025.157958984375,
"y":214.63067626953125
}
],
"name" : "David",
"num" : "639751885937",
"sex" : "Male",
"birth" : "20000101",
"success" : true
}
Query address: $.address or $[‘address’]
Query the value of x in the first array in card_region: $.card_region[0].x or $.card_region[0]['x']
You can test and evaluate JSON Path at https://jsonpath.com.