Querying direct children of root element with jsonpath

佐手、 提交于 2019-12-13 05:14:21

问题


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

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

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)

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?


回答1:


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

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/



来源:https://stackoverflow.com/questions/36843690/querying-direct-children-of-root-element-with-jsonpath

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