jsonjmeterbeanshelljsr223

Parse API Json response in JMeter and create a payload by modifying few values based on certain criteria


I am trying to parse the whole response from API 1 in JMeter and make few changes in the payload and pass it to next API.

For an Instance, I am fetching below response from API 1:

{ "environments": [ { "id": "123", "databases": [ { "environmentType": "abc", "dbName": "DB1", "dbSize": 10, "provisionType": "serverless", "vCores": 2 }, { "environmentType": "abc", "dbName": "DB2", "dbSize": 10, "provisionType": "serverless", "vCores": 2 } ] } ] }

Now I need to modify the provision type as "provisioned" and vCores as 4 only if dbName is "DB2" and rest all payload should remain same. This modified json payload has to be passed as an input in API 2.

I tried parsing in JSR223 postprocessor using below libraries but facing issues while preparing the required request for API 2.

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

Need some help on this.


Solution

  • You could add a JSR223 PostProcessor as a child of the request which returns the above JSON and put the following code into "Script" area:

    def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
    
    json.environments.each { environment ->
        environment.databases.each { database ->
            if (database.dbName == "DB2") {
                database.vCores = 4
                database.provisionType = "provisioned"
            }
        }
    }
    
    vars.put('payload', new groovy.json.JsonBuilder(json).toPrettyString())
    

    the generated payload can be accessed as ${payload} where required

    More information: