Search code examples
jsonjmeter

How to merge two json blocks with some condition and to pass the merged json in subsequent request


I need to merge two json blocks with some condition and to pass the merged json in subsequent request, For example below is the json body we get from the response of a request,

"Extras": [
{
    "ExtraId": "528",
    "IsMandatory": true,
    "Options": [
        {
            "OptionId": "712",
            "NetCost": {
                "Amount": 22.0,
                "Currency": "EUR"
            }
        },
        {
            "OptionId": "713",
            "NetCost": {
                "Amount": 34.0,
                "Currency": "EUR"
            }
        }
    ]
},
{
    "ExtraId": "529",
    "IsMandatory": true,
    "Options": [
        {
            "OptionId": "714",
            "NetCost": {
                "Amount": 20.0,
                "Currency": "EUR"
            }
        },
        {
            "OptionId": "715",
            "NetCost": {
                "Amount": 32.0,
                "Currency": "EUR"
            },
        }
    ],
}
{
"ExtraId": "530",
"IsMandatory": false,
"Options": [
    {
        "OptionId": "716",
        "NetCost": {
            "Amount": 22.0,
            "Currency": "EUR"
        }
    },
    {
        "OptionId": "717",
        "NetCost": {
            "Amount": 34.0,
            "Currency": "EUR"
        }
    }
],
}
]

Requirement is to get the json in below format where IsMandatory is true and to save this in a variable so that we can send this in further request body,

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

Please help.

I am able to get the json for first block only, not able to merge the second one. Please help.


Solution

  • You can do it using i.e. JSR223 PostProcessor and the following Groovy code:

    def mandatory = new groovy.json.JsonSlurper().parse(prev.getResponseData()).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())
    

    Refer generated value as ${payload} where required

    More information: