Naseem
Naseem

Reputation: 961

How to compare the value of variable from CSV file using beanshell scripting?

I am using JSON extractor to extract the value from the response and then I need to search the CSV and get the value from the CSV for that specific value.

Like I am getting the value from JSON extractor is XYZ and then I need to search the CSV where the value is stored as

**Col1**   **Col2**
ABC    123
DEF    456
XYZ    890

Can anyone guide me to the right direction about how to fetch the value from CSV using bean shell?

Thanks.

Upvotes: 1

Views: 630

Answers (2)

Dmitri T
Dmitri T

Reputation: 168072

Don't use Beanshell for scripting, go for JSR223 Elements and Groovy language instead. Beanshell has known performance problems and it will become your test's bottleneck assuming large number of users.

The relevant Groovy code would be something like:

def writer = new StringWriter()
new File('/path/to/your/file.csv').filterLine(writer) { line ->
    line.contains(vars.get('VARIABLE_FROM_JSON_EXTRACTOR_REFERENCE_NAME'))
}

def value = writer.toString().split(",")[1].replace(System.getProperty('line.separator'), '')

vars.put('value', value)

You will be able to access the value from CSV file as ${value} where required.

References:

Upvotes: 2

Ori Marko
Ori Marko

Reputation: 58772

Read lines, Use split by comma to get columns values Find column value XYZ and assign column 2 value to jmeter variable:

  Scanner scanner = new Scanner(new File(flatFile));
  scanner.useDelimiter("\r\n");
  while (scanner.hasNext()) {
    String line = scanner.next();
    String cells[] = line.split(",");  

       if (cells[0].equals("XYZ")) {
         vars.put("myVal2",  cells[1]);
        }
       }  

Upvotes: 1

Related Questions