Karate - How change key name in JSON

Viewed 161

I have the following JSON. I want to change the keyName 'freeDelivery' to 'isFreeDelivery' but I can't figure out how to do it.

{
    "result": [
        {
            "deliverySlots": [
                {
                    "id": "2DNN",
                    "date": "2022-04-05",
                    "freeDelivery": false,
                    "label": "All day delivery 08:30am to 5pm",
                    "price": "£5.00",
                    "fullSlotId": "2DNN"
                },
                {
                    "id": "2DPM",
                    "date": "2022-04-05",
                    "freeDelivery": false,
                    "label": "Afternoon 12pm to 5pm",
                    "price": "£10.00",
                    "fullSlotId": "2DPM"
                }
                ]
        },
        {
            "deliverySlots": [
                {
                    "id": "2DNN",
                    "date": "2022-04-06",
                    "freeDelivery": false,
                    "label": "All day delivery 08:30am to 5pm",
                    "price": "£5.00",
                    "fullSlotId": "2DNN"
                },
                {
                    "id": "2DPM",
                    "date": "2022-04-06",
                    "freeDelivery": false,
                    "label": "Afternoon 12pm to 5pm",
                    "price": "£10.00",
                    "fullSlotId": "2DPM"
                }
            ]
        }
    ]
}

I've looked at the following pages but still can't figure out how to do it. Do I have to do a transorm or is there an easier way?

https://github.com/karatelabs/karate/blob/master/karate-junit4/src/test/java/com/intuit/karate/junit4/demos/js-arrays.feature https://github.com/karatelabs/karate#json-transforms

1 Answers

Here you go:

* def payload = { before: 'foo' }
* remove payload.before
* payload.after = 'bar'
* match payload == { after: 'bar' }

Instead of remove this will also work (using pure JS):

* eval delete payload.before

EDIT: after seeing the comments, I would treat this as a JSON transform.

* def payload = { before: 'foo' }
* def fun = function(x){ var res = {}; res.after = x.before; return res }
* def result = fun(payload)
* match result == { after: 'foo' }

I'm sure now you'll want to "retain" all the existing data. Fine, here you go:

* def payload = { before: 'foo' }
* def fun = function(x){ var res = x; res.after = x.before; delete res.before; return res }
* def result = fun(payload)
* match result == { after: 'foo' }

And you already know that you can run a transform on all array elements like this:

* def result = karate.map(someArray, fun)

Please note that you can create 2 or 3 transforms - and "nest" them.

Related