'How to count JSON Objects in array filtered by attribute of the object by JSONPath
I'm writing a JSONPath expression that counts objects in an array while filtering by one of the field of the object.
Input JSON taken from http://jsonpath.herokuapp.com/
{
"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 my expression that extracts object where "category" is "fiction".
$.store.book[?(@.category == "fiction")]
The output is as expected.
[
{
"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
}
]
So far so good. What I would like to achieve is to count the number of objects in the array. In this case 3. I tried this expression:
$.store.book[?(@.category == "fiction")].length()
The output is not what I expected.
[
4,
5,
5
]
The below didn't work either
$.store[?(@.book[*].category == "fiction")].length()
How do I count the number of elements in the array? If I use jq
it could be written as
[.store.book[] | select (.category == "fiction")] | length
Solution 1:[1]
Very late for the answer but I came across this scenario recently and managed to get the number of object inside the array using below JsonPath query as per the JSON provided in question:
$.length($.store.book[?(@.category == "fiction")].length())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Reyan Chougle |