I have a JSON array that contains 4 objects each with an id
field. The fourth object contains two children that each also have an id
field. I want to only get the ids of the 4 top level children; I don't want the ids of the children of the 4th element.
This is a simplified version of the JSON string:
[
{
"id": 709709537
},
{
"id": 1104067257
},
{
"id": 2961327618
},
{
"id": 9066007668,
"photo": {
"id": 461295287,
"thumbnails": [
{
"id": 461295307
}
]
}
}
]
Using JSONPath, $..id
will get me all 6 id elements, with no way to determine which level they come from, e.g.
[
709709537,
1104067257,
2961327618,
9066007668,
461295287,
461295307
]
I expected $.id
to give me the 4 top level id
children, but this gets me nothing.
I've researched many pages and tried several experiments using JSON testers (e.g. https://jsonpath.curiousconcept.com/) and cannot find a JSONPath expression to get just the top 4 children id elements.
Is there a JSONPath expression that will get me just the top level children ids?
JSONPath is a query language for JSON, similar to XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.
JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. The "root member object" in JsonPath is always referred to as $ regardless if it is an object or array. JsonPath expressions can use the dot–notation.
The Jayway JsonPath library has support for reading values using a JSON path. If you would like to specifically use GSON or Jackson to do the deserialization (the default is to use json-smart), you can also configure this: Configuration.
JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the Groovy dot notation syntax when getting an object from the document. You can regard it as an alternative to XPath for XML.
I think it should be
$[*].id
Remember that you have these in an array, and you want each element in the array. Then you want their .id afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With