Find object in nested data by property value (with

2019-04-21 10:45发布

问题:

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:

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