Search code examples
jsonjsonpath

Using JSONPath to get only top level children


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?


Solution

  • 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.