User51610
User51610

Reputation: 493

Karate filtering json response

In my Karate tests (0.9.4), I have a json response like the following:

[
    {
        "id": "id_number_1",
        "name": "name"
    },
    {
        "id": "id_number_2",
        "name": "name 2",
        "nestedThing" {
            "id": "another_id",
            "name": object2_name"
        }
    },
    {
        "id": "id_number_3",
        "name": "name 3"
    }
]

Some of the objects in the response will have a nestedThing and others will not. First, I want to get rid of all the items in the list that do not have nestedThing. Second, once that's done, I want to def a list that only contains the first-level id fields. So, it would look like:

["id_number_1", "id_number_3"]

Upvotes: 1

Views: 1620

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

This can be done in one line:

* def ids = response.filter(x => !x.nestedThing).map(x => x.id)

Refer: https://github.com/karatelabs/karate#json-transforms

EDIT: the below works in versions 0.9.X

* def temp = karate.filter(response, function(x){ return !x.nestedThing })
* def ids = karate.map(temp, function(x){ return x.id })
* match ids == ['id_number_1', 'id_number_3']

Upvotes: 1

Related Questions