Search code examples
apijmeterresponse

Jmeter array Response, getting the sum and extracting


Hello does anyone know how to simulate this scenario.

Example response: { "data": "[1,2,3,4,5,6,7]", "success": true, "message": { "code": "S", "message": "Get Count Success" } }

I want to add all data values and extract that. Note: the data value is dynamic sometimes the content 3 sometimes 5 and etc.

Thank you so much in advance.


Solution

    1. Add JSR223 PostProcessor as a child of the request which returns the above JSON

    2. Put the following code into "Script" area:

      import groovy.json.JsonSlurper
      
      def data = new JsonSlurper().parse(prev.getResponseData()).data
      
      def numbers = new JsonSlurper().parseText(data)
      
      def sum = numbers.sum()
      
      log.info('Sum of numbers is: ' + sum)
      
      vars.put('sum', sum as String)
      
    3. That's it, you will be able to access the sum of all numbers in "data" attribute as ${sum} where required. Also the sum will be printed to jmeter.log file:

      enter image description here

    More information: