21

I have this test data:

[
  {
    id: 1,
    l: 'a',
    sub: [
      ]
  },
  {
    id: 2,
    l: 'b',
    sub: [
      {
        id: 4,
        l: 'd'
      },
      {
        id: 5,
        l: 'e'
      },
      {
        id: 6,
        l: 'f',
        sub: [
          {
            id: 7,
            l: 'g'
          }
        ]
      }
    ]
  },
  {
    id: 3,
    l: 'c',
    sub: []
  }
];

And I'm trying to get the path of the object with id: 7. I tried quite some JSONPath queries, but I just can't seem to fiind out how to make JSONPath iterate over all sub keys and search in there.

How can I match the object with id: 7?

Here is my testing plunkr: http://plnkr.co/edit/RoSeRo0L1B2oH3wC5LdU?p=preview

1 Answer 1

36

This query should work for what you are doing:

$..[?(@.id==7)]

You need to remove the id just after the $.. as you want to select the whole object, not just the id. You were also missing the square brackets around the query.

This query brings back the following result set:

[
    {
        "id": 7,
        "l": "g"
    }
]

If you just want to retrieve the value of the l property (since you already know the id), you can easily do that as well. Just add .l at the end of the query:

$..[?(@.id==7)].l

This brings back the following result set:

[
    "g"
]

I tested the first query out here using this online json path tester tool and using your plunker: http://www.jsonquerytool.com/sample/jsonpathfilterallbypropertyvalue

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.