0
votes

I have a Csv file with multiple records(comma Seperated), i need a groovy script that can fetch all the data's from csv and make a json array and send a POST request in jmeter. Here is my code below. But it only fetches one record

import groovy.json.*
import groovy.json.JsonBuilder

def jsonBuilder = new groovy.json.JsonBuilder()
jsonBuilder {
    id Integer.parseInt(vars.get("id"))
    name vars.get("first_name")
    last_name vars.get("last_name")
    email vars.get("email")
    institute_id Integer.parseInt(vars.get("institute_id"))
    category_id Integer.parseInt(vars.get("category_id"))
    value Boolean.parseBoolean(vars.get("value"))
}

sampler.addNonEncodedArgument("",jsonBuilder.toPrettyString(),"")
sampler.setPostBodyRaw(true) 
1
Could you please also post what the variable vars is?Gergely Toth
vars (JMeter variables) is the most frequently used component. It's an instance of the org.apache.jmeter.threads.JMeterVariables class and provides read/write access to current variables, is capable of enumerating/changing existing variables, creating new ones, and obtaining nested properties.ejustin
How the desired json would look like?Rao
{ "_token": "sometokentext", "candidate": [{ "id": 1, "first_name": "lorem ipsum", "last_name": "lorem ipsum", "email": "[email protected]", "institute_id": loremipsum, "category_id": loremipsum, "value": false }], "test_id": "${id}", "selectedDate": "${date}" }ejustin
I don't understand why you need groovy script at all? Why not put JSON (exactly as you posted it in the comment above) directly in the HTTP Sampler, i.e. HTTP Sampler body { "_token": "sometokentext", "candidate": [{ "id": 1, "first_name": "${first_name}", "last_name": "${last_name}", "email": "${email}", "institute_id": ${institute_id}, "category_id": ${category_id}, "value": ${value} }], "test_id": "${id}", "selectedDate": "${date}" }Kiril S.

1 Answers

2
votes

Assuming you have the following CSV file:

id,first_name,last_name,email,institute_id,category_id,value
1,john,doe,[email protected],1,1,true
2,jane,doe,[email protected],2,2,false

You can convert it into a JSON Array using below Groovy code:

    import groovy.json.JsonOutput

    def lines = new File('test.csv').readLines()

    def keys = lines[0].split(',')
    def rows = lines[1..-1].collect { line ->
        def i = 0, vals = line.split(',')
        keys.inject([:]) { map, key -> map << ["$key": vals[i++]] }
    }

    log.info(JsonOutput.prettyPrint(JsonOutput.toJson(rows)))

Demo:

Groovy CSV to JSON

References: