Converting CSV to hashmap - groovy scripting jmeter

70 Views Asked by At

I already created a dynamic xml request payload and I'm pulling some data from CSV file. Now im having a hardtime to convert csv rows and column to hashmap since im a bit new to Groovy scripting.

My csv looks like this

itemId, name, lastname
12345, n1, ln1
54321, n2, ln2
66666, n3, ln3
....

What I want to achieve is like this

{
    "12345": [
        " n1",
        " ln1"
    ],
    "54321": [
        "n2",
        "ln2"
    ] .............
}

My code is here

def source = new File('1000items.csv').readLines()
def payload = [:]

source.takeRight(source.size() - 1).each { line ->
    payload.put(line.split(',')[0], ----STUCKED HERE----)
}

PS. I'm following this guide but im stucked on building the hashmap part

Jmeter SOAP parameterization with dynamically changing tag blocks

2

There are 2 best solutions below

1
On BEST ANSWER

Just pass a List as the 2nd argument and fill it with the remaining values from the current line.

Something like:

source.takeRight(source.size() - 1).each { line ->
    def entry = line.split(',')
    payload.put(entry[0], [entry[1], entry[2]])
}

More information:

0
On
def data = '''itemId, name, lastname
12345, n1, ln1
54321, n2, ln2
66666, n3, ln3
'''

//instead if `data` you can use `new File(...)`
def payload = data.readLines()
       .tail()
       .findAll{it}                 //filter out empty lines 
       .collect{it.split(',\\s*')}  //split by coma and optional spaces
       .collectEntries{ [it[0], [it[1], it[2]]] }

println new groovy.json.JsonBuilder(payload).toPrettyString()

all groovy List methods you can find here:

https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/List.html