Search code examples
jmeterjmeter-5.0jmeter-4.0jmeter-3.2

How to prepare the JSON payload from the response in JMeter


I am getting response from one API and need to prepare the payload from that response. For example the response as like

    {
      "data": {
        "total_count": 5,
        "userIds": [1,2,3,4,5]
   }

Need to make the payload from the response to other API like

{
"users": [
      {
        "user_id": 1,
        "invite_amount": 100,
      },
      {
        "user_id": 2,
        "invite_amount": 100
      },
      {
        "user_id": 3,
        "invite_amount": 100
      },
      {
        "user_id": 4,
        "invite_amount": 100
      },
      {
        "user_id": 5,
        "invite_amount": 100
      }
    ]
}

Above payload need to send to the another API


Solution

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

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

      def userIds = new groovy.json.JsonSlurper().parse(prev.getResponseData()).data.userIds
      
      def payload = [:]
      
      def users = []
      userIds.each { userId ->
          def user = [:]
          user.put('user_id', userId)
          user.put('invite_amount', 100)
          users.add(user)
      }
      payload.put('users', users)
      
      vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
      
    3. That's it, you will be able to refer the generated payload value as ${payload} where required

    More information: