jmeterjsr

An Extra pair of curly braces is coming using JSR223 post processor with groovy


We are using a JSR223 code to make an json object using below code,

def mandatory = new groovy.json.JsonSlurper().parse(prev.getResponseData()).Properties.Room.Extras.findAll { extra -> extra.IsMandatory }

def payload = []
mandatory.each { extra ->
    def item = [:]
    item.put('ExtraId', extra.ExtraId)
    item.put('OptionId', extra.Options[0].OptionId)
    item.put('ExpectedNetCost', extra.Options[0].NetCost)
    payload.add(item)
}

vars.put('payload', new groovy.json.JsonBuilder([Extras: payload]).toPrettyString())

we are using 'toPrettyString' as well but still getting an extra pair of curly braces (at the start and end). Can someone please help to remove this !

I have tried this link After updating json file with groovy, the file data contains extra curly brackets and "content" object

but solution doesn't work for me.


Solution

  • If you don't want to have the generated value as a JSON Object you can replace this line:

    vars.put('payload', new groovy.json.JsonBuilder([Extras: payload]).toPrettyString())
    

    with this line:

    vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
    

    In this case you will have only the JSON Array, to wit your output will be:

    [
      {
        "ExtraId": "528",
        "OptionId": "712",
        "ExpectedNetCost": {
          "Amount": 22.0,
          "Currency": "EUR"
        }
      },
      {
        "ExtraId": "529",
        "OptionId": "714",
        "ExpectedNetCost": {
          "Amount": 20.0,
          "Currency": "EUR"
        }
      }
    ]
    

    More information: