Search code examples
jmeterbeanshell

Why my JSON values are getting duplicated in Jmeter?


Here is my BeanShell script which I wrote in JMeter

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


JSONObject outerObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(int i = 0;i<=3;i++)
{   

    JSONObject innerObject = new JSONObject();
    innerObject.put("middleName", "${__RandomString(4,KLMNOPRSTUVWXYZ,)}");
    innerObject.put("maidenName", "${__RandomString(4,HUDNSERTFG,)}");
    innerObject.put("gender", "${__RandomString(1,MFU,)}");
    innerObject.put("TestingType", "${__RandomString(1,IE,)}");
    jsonArray.put(innerObject);
    outerObject.put("nameList", jsonArray);
    
}
    
    outerObject.put("Alert", "Testing Alert");
    
    log.info(outerObject.toString());
    vars.putObject("jsonData",jsonArray);

Here is the JSON response which I am getting

{
  "nameList": [
    {
      "gender": "M",
      "maidenName": "DUDT",
      "middleName": "ZPMZ",
      "TestingType": "E"
    },
   {
      "gender": "M",
      "maidenName": "DUDT",
      "middleName": "ZPMZ",
      "TestingType": "E"
    },
    {
      "gender": "M",
      "maidenName": "DUDT",
      "middleName": "ZPMZ",
      "TestingType": "E"
    },
    {
      "gender": "M",
      "maidenName": "DUDT",
      "middleName": "ZPMZ",
      "TestingType": "E"
    }
  ],
  "Alert": "Testing Alert"
}

enter image description here enter image description here

As you can see the JSON above, all the values are duplicated. I want to have different values for all the variable. Am I missing anything? Please guide me if anything wrong with my code. Thanks.


Solution

  • I would suggest using JSR223 + Groovy for performances with below code using RandomStringGenerator:

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.apache.commons.text.RandomStringGenerator;
    
    JSONObject outerObject = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    RandomStringGenerator generator = new RandomStringGenerator.Builder().selectFrom("KLMNOPRSTUVWXYZ".toCharArray()).build();
    RandomStringGenerator generatorGender = new RandomStringGenerator.Builder().selectFrom("MFU".toCharArray()).build();
    RandomStringGenerator generatorType = new RandomStringGenerator.Builder().selectFrom("IE".toCharArray()).build();
    
    for(int i = 0;i<=3;i++)
    {   
        JSONObject innerObject = new JSONObject();
        innerObject.put("middleName", generator.generate(4));
        innerObject.put("maidenName", generator.generate(4));
        innerObject.put("gender", generatorGender.generate(1));
        innerObject.put("TestingType", generatorType.generate(1));
        jsonArray.put(innerObject);
        outerObject.put("nameList", jsonArray);
    }
    
    outerObject.put("Alert", "Testing Alert");
    log.info(outerObject.toString());
    vars.putObject("jsonData",jsonArray);