问题
I have an array in JSON and I would like to apply two filters to it like so:
$._embedded.values[0]._embedded.data[?(@.var1='value1' && @.var2='value2')]
I need to select only those elements from the array that satisfies the AND operation. However, in practice this doesn't appear to work.
Is it possible to do this or must I perform a two step action to extract one set then filter again to get my final results?
回答1:
As far as I know AND / OR are not supported yet. But you can get relatively close with this [,] array. But even this made me wonder when I tested it. There's some strange behaviour. I took an example JSON string from the Jayway JsonPath Evaluator and put it into JsonPath Expression Tester (because it didn't work with Jayway when I tried).
So the JSON I've tested with the curiousconcept version is:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
And the expression:
$..book[?(@.price==8.99),?(@.category=='fiction')]
which results in:
[
{
"category":"fiction",
"author":"Herman Melville",
"title":"Moby Dick",
"isbn":"0-553-21311-3",
"price":8.99
}
]
what seems to be perfect. (take the price 8.99 AND category 'fiction'... perfect!)
BUT: change it to:
$..book[?(@.category=='fiction'),?(@.price==8.99)]
then the output is:
[
]
It seems to me that [,] is not well implemented in Jayway JsonPath Tester as well as curiousconcept.com expression tester.
But from what I know they're working on an (real) implementation of AND and or (issue27 here at google code).
Hope this clarifies at least something!
回答2:
The Jayway implementation supports inlined AND and OR criteria.
$..book[?(@.price==8.99 && @.category=='fiction')]
[
{
"category" : "fiction",
"author" : "Herman Melville",
"title" : "Moby Dick",
"isbn" : "0-553-21311-3",
"price" : 8.99
}
]
Try it out and compare different implementations here http://jsonpath.herokuapp.com/
回答3:
below is an example showing JSON path with AND and OR criteria:
Get all books with price less than 10 and of 'fiction' category
$..book[?(@.price<10 && @.category=='fiction')]
Get all books with price less than 10 or any book of 'fiction' category
$..book[?(@.price<10 || @.category=='fiction')]
You can also try mixing up AND and Or criteria:
Get books of 'Herman Melville' with with price less than 10 or his book of 'fiction' category
$..book[?(@.author=='Herman Melville' && (@.price<10 || @.category=='fiction'))]
来源:https://stackoverflow.com/questions/29703891/jsonpath-and-operator-on-array