Forum Discussion

Lucian's avatar
Lucian
Community Hero
7 years ago

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.*' )
  • JoostDG's avatar
    JoostDG
    Frequent Contributor

    Hi Lucian,

     

    I am trying to find a groovy solution to find a certain count.  I have a rest request "myrestrequest", where part of the response is:

    ...

    "hasData" : [
    "https://test.api/1",
    "https://test.api/2",
    "https://test.api/3"
    ]

    ...

     

    The json path count match assertion in myrestrequest perfectly asserts : $['hasData'] = 3.

     

    But now I want to use that result of that count somewhere else in a groovy script. I struggle to find a way to do this.

     

    When I go get the data via context.expand ('${myrequest#Response#$[\'hasData\']}, I get the hasData array as a String. In other cases I can use the jsonSlurper or jsonUtl.parseTrimmerText commands to make convert it to an array again and use .size(), but with this specific example that doesn't work.

     

    Any thoughts? 


    Thanks in advance!

     

    • Lucian's avatar
      Lucian
      Community Hero

      You can use the script I wrote and then pass the resulted value into a property like:

       

      testRunner.testCase.setPropertyValue( "ElementsCount", countElement.toString() )
      

      That property can later be used in a groovy or directly in a request.

      ${#TestCase#ElementsCount}
      • JoostDG's avatar
        JoostDG
        Frequent Contributor

        Hi Lucian,

         

        Yes, I thought of that solution also, but I found the answer: It just looks like I did not grasp fully the script you provided. 

         

        I just had to use the full response from "myrestrequest" and then define the jsonObject like :

        import static com.jayway.jsonpath.JsonPath.parse
        def response = context.expand( '${myrestrequest#Response}' )
        def countElement( String json, String jsonPath ) {
        return parse( json ).read( jsonPath ).size()
        }
        def jsonObject = response
        log.info countElement( jsonObject, '$.hasData.*' )

         Thanks for this!!