Search code examples
jsonjmeterhttprequesthttpresponsebeanshell

Jmeter - Passing specific JSON response to HTTP request dynamically


I am having a specific requirement in Jmeter(2.13) where i need to pass two parameters multiple times dynamically as id and parentObjectApiName

{
            "id":"SomeNumber",
            "parentObjectApiName":"SomeName"
         },
         {
            "id":"SomeNumber",
            "parentObjectApiName":"SomeName"
         },

}

Which i will be getting from a response as :

{
    "detailMap": {
      "RootNumber": [
        {
          "id": "SomeNumber",
          "properties": {

          },
          "isDeleted": false,
          "version": "2017-11-20T08:13:30+00:00",
          "referenceId": null,
          "parentObjectApiName": "SomeName"
        },
        {
          "id": "SomeNumber",
          "properties": {

          },
          "isDeleted": false,
          "version": "2017-04-21T15:40:10.742+00:00",
          "referenceId": null,
          "parentObjectApiName": "SomeName"
        },
        {
        :
        },
      ]
    }
    "state": {
      "errorDetails": []
    }
  }

Is there any workaround for the above requirement by using beanshell in Jmeter(2.13).


Solution

  • Your requirement can be achieved by following the steps below.

    1. Add "JSON Extractor" to the request where the response contains the parameters which you want to pass in next request.(Image-1)
    2. JSON Extractor configuration(Image-2)

    Keeping the JSON Extractor as it is, Add "Beanshell PostProcessor" to the request and keep the following part of code and try. Your desired id & parentObjectApiName will be stored in variable "json". You can call it in your next request as ${json}

    import java.io.file;
    import java.util.*;
    import org.apache.jmeter.services.fileserver;
    
    StringBuilder output = new StringBuilder();
    Random random = new Random();
    int max = Integer.parseInt(vars.get("id_matchNr"));
    for(int i=1;i<=max;i++)
    {
    output.append("{");
    output.append("\"id\":\"" + vars.get("id_"+i) + "\",\"parentObjectApiName\":" + vars.get("parentObjectApiName_"+i));
    output.append("}").append( "," );
    }
    String withoutLastComma = output.substring( 0, output.length( ) - ",".length( ) );
    vars.put("json", withoutLastComma.toString());
    

    Image-1

    Image-2