Jmeter generate json payload of request dynamically

19,768
  1. Add a Beanshell PreProcessor as a child of the request you want to parametrize
  2. Put following code into the PreProcessor's "Script" area:

    StringBuilder result = new StringBuilder();
    String newline = System.getProperty("line.separator");
    int max = Integer.parseInt(Parameters);
    Random random = new Random();
    
    result.append("{");
    result.append("\"productIds\" : [");
    result.append(newline);
    for (int i = 1; i < max; i++) {
        result.append("\"").append(random.nextInt()).append("\",");
        result.append(newline);
    }
    result.append("]");
    result.append(newline);
    result.append("}");
    
    vars.put("json", result.toString());
    
  3. Put your ${productsCount} value into "Parameters" stanza
  4. Refer generated payload as ${json} where required

See How to use BeanShell: JMeter's favorite built-in component guide for more details on Beanshell scripting in Apache JMeter.

Share:
19,768

Related videos on Youtube

Diego Martinoia
Author by

Diego Martinoia

I press buttons. No, really, that's my job, hobby, life, sleep. #SOreadytohelp

Updated on September 15, 2022

Comments

  • Diego Martinoia
    Diego Martinoia over 1 year

    I have a Jmeter test plan where I want my HttpSampler to send a post request.

    The body of the request should contain Json as follows:

    {
      "productIds" : [
        "p1",
        "p2",
        ...
      ]
    }
    

    I have setup a random variable generator that returns well-formed productId with every call. What I would like to do is generating the payload by filling productIds of random pid's taken from the generator, directly in the body of the request. Something like (suppose *** is the scripting escape):

    {
      "productIds" : [
         ***
           for i in (1, $productsCount) {
             write("\"$randomPid\"\n")
           }
         ***
      ]
    }
    

    Is it possible? If yes, how? If not, how would you approach the issue?

    Thanks!

  • Diego Martinoia
    Diego Martinoia over 9 years
    Yeah, that's the way I did it before seeing your answer, was wondering if it was possible to do within the http request payload directly, but this is also ok. Thanks!
  • Dmitri T
    Dmitri T over 9 years
    You can use __Beanshell function right in the request body but the whole approach from coding perspective will be the same