Search code examples
jmeterexport-to-csvjsr223json-extract

How to store 2 variable's value into .csv file as 2 separate columns using JSR223 listener in Jmeter


I have two variables whose values i have extracted from the response body using JSON Extractor [Here is the image showing two variables][1] [1]: https://i.sstatic.net/E0RKx.png

In JSR223 PostProcessor, I have written below code which prints all the values in 1st column, but I want 2 separate columns variable wise.

import org.apache.commons.io.FileUtils
import java.text.SimpleDateFormat;
// Get total number of matches. (Returns string)
def resultCount = vars.get("AppObjectName_matchNr")
log.warn 'Output to jmeter console' +  resultCount
// Generate timestamp to create uniue file name.
String fileSuffix = new SimpleDateFormat("ddMMyyyyHHmm").format(new Date())
// Create file Object
f = new File("results_Kr"+fileSuffix+".csv")
for (int i=1; i<=resultCount.toInteger(); i++)
{
  // Get each matching result one by one.
  records = vars.get("AppObjectName_" +i)
  Query = vars.get("QueryName_" + i)
// Write result to csv file.
  FileUtils.writeStringToFile(f,records + System.getProperty("line.separator"),true)
  FileUtils.writeStringToFile(f,Query + System.getProperty("line.separator"),true)
}

[Here is the image of code which creates .csv file & write both variables values in one column only][2] [2]: https://i.sstatic.net/bVIeb.png


Solution

    1. Change first FileUtils.writeStringToFile function call to:

      FileUtils.writeStringToFile(f,records + ',' + Query + System.getProperty("line.separator"),true)
      
    2. Remove second function call completely

    Also be aware that in case of minimal concurrency when 2 or more threads will be writing data into the same file it might result into data corruption or loss so if this is the case - consider using either Flexible File Writer or convert the variables into JMeter Properties and write them in tearDown Thread Group.