按属性值在嵌套数据中查找对象(使用JSONPath) [英] Find object in nested data by property value (with JSONPath)

查看:299
本文介绍了按属性值在嵌套数据中查找对象(使用JSONPath)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个测试数据:

[
  {
    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: []
  }
];

我正在尝试使用 id获取对象的路径: 7 。我尝试了一些JSONPath查询,但我似乎无法弄清楚如何让JSONPath迭代所有 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.

如何将对象与 id匹配:7

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

推荐答案

此查询应该适用于您正在做的事情:

This query should work for what you are doing:

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

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

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"
    }
]

如果你只想检索l属性的值(因为你已经知道了id),你可以很容易地做到那也是。只需在查询结尾添加 .l

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

这会带回以下结果集:

[
    "g"
]

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

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

这篇关于按属性值在嵌套数据中查找对象(使用JSONPath)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆