使用jsonpath查询根元素的直接子级 [英] Querying direct children of root element with jsonpath

查看:64
本文介绍了使用jsonpath查询根元素的直接子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用jsonpath匹配根元素的直接子代时遇到问题.有这样的数据:

I have a problem with matching direct children of a root element using jsonpath. Having such a data:

{"name": "lorem", "age": 15}

如何检查此json是否具有值为"lorem"的字段"name"?我尝试过这样的事情:

How can I check if this json has a field "name" with value "lorem"?. I tried something like this:

$[?(@.name == "lorem")]

但是它返回一个空数组,因为(我猜)它在结构的更深处搜索字段名称".所以我尝试了:

but it returns an empty array, because (I guess) it search for a field "name" deeper in the structure. So I tried:

$[?(@ == "lorem")]

但是它也不起作用(语法不正确)

But it didn't work also (incorrect syntax)

但是-当json结构中的查询字段更深"时,它可以工作.有了这个json数据:

However - it works, when queried field is "deeper" in json structure. With this json data:

{"name": {"realName": "lorem"}, "age": 15}

此查询按预期方式工作,返回非空结果:

this query works as expected, returning non-empty result:

$[?(@.realName == "lorem")]

似乎不可能对作为根元素的直接子级的字段执行类似的查询.我说得对吗?

It seems like there is no possibility to perform similar query for fields that are direct children of root element. Am I correct?

推荐答案

重要的是指出您使用的语言和实现. JSONPath是一个有用的开始,但它是非正式的且未指定.

It's important to indicate what language and implementation you are using. JSONPath was a helpful beginning, but informal and underspecified.

使用 jsonpath-plus ,您可以使用@进行检查根目录下的值,但是如果要确保您使用的是正确的属性,则还需要使用其自定义的@property值:

Using jsonpath-plus, you can use @ to check the value at root, but if you want to ensure you are on the correct property, you will also need to use its custom @property value:

var json = {"name": "lorem", "age": 15};
var path = '$[?(@property == "name" && @ == "lorem")]';
JSONPath({json: json, path: path, wrap: false});

https://jsfiddle.net/vq1dm792/

这篇关于使用jsonpath查询根元素的直接子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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