I have a JSON response from the Facebook API that looks like this:
{
"data": [
{
"name": "Barack Obama",
"category": "Politician",
"id": "6815841748"
},
{
"name": "Barack Obama's Dead Fly",
"category": "Public figure",
"id": "92943557739"
}]
}
I want to apply JSONPath to it to only return results with a category of "Politician". From what I've read, it appears that I need to do:
$.data[?(@.category=='Politician')]
but according to the testing tool I found, this doesn't work. I found another question which suggests that I should use "eq" instead of "==", but that doesn't work either. What am I getting wrong here?
Drop the quotes:
See also this Json Path Example page
I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.
Here's the syntax and an abbreviated sample twitter document below.
This site was useful for testing:
The jsonpath filter expression:
Test document:
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
And the expression:
$.store.book[?(@.length-1)].title
, the tool returns a list of all titles.''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:
DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:
The browser testing tools while convenient can be a bit deceiving. Consider:
Most tools returned this as false:
But when I executed against
It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.