javascript 按属性值查找嵌套数据中的对象(使用 JSONPath)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30680515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:31:22  来源:igfitidea点击:

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

javascriptjsonpath

提问by alexandernst

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 subkeys and search in there.

我正在尝试使用id: 7. 我尝试了相当多的 JSONPath 查询,但我似乎无法找出如何让 JSONPath 遍历所有sub键并在其中进行搜索。

How can I match the object with id: 7?

我怎样才能匹配对象id: 7

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

这是我的测试 plunkr:http://plnkr.co/edit/RoSeRo0L1B2oH3wC5LdU?p=preview

回答by Duncan

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.

您需要在 id 之后删除 id,$..因为您要选择整个对象,而不仅仅是 id。您还缺少查询周围的方括号。

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 .lat the end of the query:

如果您只想检索 l 属性的值(因为您已经知道 id),您也可以轻松地做到这一点。只需.l在查询的末尾添加:

$..[?(@.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

我在这里使用此在线 json 路径测试器工具并使用您的 plunker 测试了第一个查询:http: //www.jsonquerytool.com/sample/jsonpathfilterallbypropertyvalue