Find object in nested data by property value (with JSONPath)

↘锁芯ラ 提交于 2019-12-06 22:10:54

问题


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



来源:https://stackoverflow.com/questions/30680515/find-object-in-nested-data-by-property-value-with-jsonpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!