Lucian
7 years agoCommunity Hero
Sharing is caring - groovy script to count json elements found by a jsonPath query
Following Olga_T's suggestion here is a script to count the number of elements found by a jsonPath query:
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.*' )