Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSONPath to get only top level children

Tags:

json

jsonpath

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?

like image 561
user2970051 Avatar asked Oct 28 '16 20:10

user2970051


People also ask

What is JsonPath used for?

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.

What is a JsonPath expression?

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.

Does Jackson support JsonPath?

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.

What is JSON path in REST assured?

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.


1 Answers

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.

like image 174
Nol Avatar answered Oct 23 '22 01:10

Nol