Search code examples
arraysjsonjmeterhttp-post

JMeter: Need to send all values in a CSV File to different variables in a request body, based on some criteria


I have a CSV file, which has some user details, like their employee id (123456) and email id (abc@xyz.com). The employee id/email id of the users are present in the first column, and the second column contains the type of the id (employee id/email id). It looks like below:

id idType
123456 empid
abc@xyz.com emailid
111111 empid
ghi@xyz.com emailid

In the body of the HTTP request (JSON), I need to pass these values to different variables, based on the id type given in the CSV file. For example, if the id type id empid, I need to pass those values to empid array; and so on. I want the passed values to look like below:

{"empid":["123456", "111111"], "emailid":["abc@xyz.com", "ghi@xyz.com"]}

If the value is passed to a single variable, I can achieve the same using User Parameters Preprocessor, but this requirement is a bit tricky. Is there any method to pass the values to the request in the above mentioned format?


Solution

  • You can do it using a suitable JSR223 Test Element, i.e.

    1. Add JSR223 PreProcessor as a child of the request which needs to have this JSON body generated

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

      def lines = new File('/path/to/your/file.csv').readLines().drop(1)
      
      def empIds = lines.findAll { line -> line.split(',')[1] == 'empid' }.collect { line -> line.split(',')[0] }
      def emailIds = lines.findAll { line -> line.split(',')[1] == 'emailid' }.collect { line -> line.split(',')[0] }
      
      def payload = ['empid': empIds, 'emailid': emailIds]
      
      vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
      
    3. Use ${payload} JMeter Variable reference in the "Body Data" tab of the HTTP Request sampler (or wherever you need to use this JSON)

    More information: