falouu
falouu

Reputation: 134

Querying direct children of root element with jsonpath

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?

Upvotes: 2

Views: 2890

Answers (1)

Brett Zamir
Brett Zamir

Reputation: 14375

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/

Upvotes: 2

Related Questions