Groovy script to count JSON elements found by a JSONPath query
Solution
The following script counts the number of elements found by a JSONPath query:
// Groovy
import static com.jayway.jsonpath.JsonPath.parse
// Define a method to count the number of elements found as a result of a jsonPath query
def countElement( String json, String jsonPath ) {
return parse( json ).read( jsonPath ).size()
}
// Create an example jsonObject
def jsonObject = '''{
"name" : "John",
"age" : 30,
"cars" : [
{
"car" : "BMW",
"color" : "red"
},
{
"car" : "Ford",
"color" : "black"
},
{
"car" : "Fiat",
"color" : "green"
}
]
}'''
// Call the previously created method with the jsonObject as a paramenter
log.info countElement( jsonObject, '$.cars.*' )
Updated 4 years ago
Version 4.0