skip to Main Content

Hi I am looking to construct a jsonpath expression to find the array element that matches the filter on a child.

Please find details below

Json

{
  "items": [
    {
      "id": 1,
      "children": [
        {"id": 101, "name": "Child1"},
        {"id": 102, "name": "Child2"}
      ]
    },
    {
      "id": 2,
      "children": [
        {"id": 201, "name": "Child3"},
        {"id": 202, "name": "Child4"}
      ]
    }
  ]
}

Expected Result

[
  {
    "id": 2,
    "children": [
      {"id": 201, "name": "Child3"},
      {"id": 202, "name": "Child4"}
    ]
  }
]

I want to find the parent element which has the children with id=201

Please find the expression I have tried with respective results.

**Expression 1:
**

$.items[?(@.children[?(@.id == 201)])]

Result:

[{"id":1,"children":[{"id":101,"name":"Child1"},{"id":102,"name":"Child2"}]},{"id":2,"children":[{"id":201,"name":"Child3"},{"id":202,"name":"Child4"}]}]
$.items[?(@.children[*].id == 201)]

Result: []

Note: I am using Jayway Library and have tried the solutions by chatgpt

Any Help would be appreciated .

Thanks in Advance

enter image description here
enter image description here

2

Answers


  1. I don’t think that Jayway supports nested queries like your first attempt.

    Note that it does work on my playground, https://json-everything.net/json-path. Mine implements the upcoming IETF specification in .Net.

    You might be able to find another library that will work for youon the comparison site.

    Login or Signup to reply.
  2. Using JsonPath-Plus
    This query on the origninal dataset:

    items[*].children[?(@.id==201)]^^
    

    will produce

    [
      { "id": 2, "children": 
        [ 
          { "id": 201, "name": "Child3" },
          { "id": 202, "name": "Child4" } 
        ]
      }
    ]
    

    $.items[*].children[?(@.id==201)]^^ produces the same result.

    The JSONPath Demo site allows you to put in a dataset, a filter/query and see the results.
    Above, the query is:

    1. Getting all the items
    2. filtering the children by the ID==201
    3. Getting the parent with the ‘^’ operator. This goes up two generations in order to get the shape of the data that you wanted.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search