0
votes

I'm quite new with scripts. I have been searching quite a while and got stuck at this point. I'm trying to create a json array at Jmeter JSR223 PreProcessor using variables from a csv file to post at Jmeter.

The json structure is;

[
    {
        "id": "${FacId}",
        "name": "${Name}",
        "type": "Facility"
    }
]

I can read the variables from csv and set the id and name as array using;

def builder = new groovy.json.JsonBuilder()

@groovy.transform.Immutable
class BSO{
    String id
    String name
}

def units = new File("/Users/gulcei/Documents/TPTest/test.csv")
    .readLines()
    .collect { line ->
        new BSO (line.split(",")[0], line.split(",")[1]) }

builder(
    units.collect(),
    type: "Facility"
)
log.info(builder.toPrettyString())
vars.put("payload",  builder.toPrettyString())

But rest of the values stays out of the array and it returns as;

[
    {
        "type": "Facility"
    },
    [
        {
            "id": "id1",
            "name": "Facility1"
        },
        {
            "id": "id2",
            "name": "Facility2"
        }
    ]
]

And one more thing; if i try to add a value with two components as;

[
    {
        "id": "${FacId}",
        "name": "${Name}",
        "type": "Facility",
        "location": {
            "latitude": 0,
            "longitude": 0
        }
    }
]

i get an "unexpected token" error. I think i'm trying to put it in the wrong format.

Can you please help me deal with it.

Thanks in advance...

1

1 Answers

0
votes

I had some help from a friend and my problem is solved now. Here is the code incase anyone else needs it;

class BSO{
    String id
    String name
    Location location
    String type
    
    BSO(id,name){
        this.id=id
        this.name=name
        this.location=new Location()
        this.type="Facility"
    }
}

class Location{
    int latitude = 0
    int longitude = 0
}

def builder = new groovy.json.JsonBuilder()
def units = new File("/Users/Documents/Test/test.csv")
                .readLines()
                .collect { line ->
                    new BSO (line.split(",")[0], line.split(",")[1])}
builder(
                units.collect()
        )
log.info(builder.toPrettyString())
vars.put("payload",  builder.toPrettyString())