Home > OS >  Gpath for JSON with nested findAll
Gpath for JSON with nested findAll

Time:10-13

I have the following response payload

[{
    "id": 1,
    "catname": "Cat01",
    "items": [{
        "Name": "Item01",
        "id": 2
    }, {
        "Name": "Item02",
        "id": 3
    }]
},
{
    "id": 4,
    "catname": "Cat02",
    "items": [{
        "Name": "Item03",
        "id": 5
    }, {
        "Name": "Item04",
        "id": 6
    }]
},
{
    "id": 7,
    "catname": "Cat03",
    "items": [{
        "Name": "Item05",
        "id": 8
    }]
}

]

I want to retrieve a list of all the items.ids (but not the ids of their parents), So this: [2, 3, 5, 6, 8]. I've tried this findAll{it}.items.findAll{it}.id but it doesn't work. Any help would be welcomed. Thanks!

CodePudding user response:

Never mind, I found the answer :). I needed to use flatten here

items.flatten().id

did the trick. I got the answer from here: How to search in anonymous and nested array using find or findAll in groovy's closures using REST-Assured library?

CodePudding user response:

You don't need to use findAll here to iterate, and you can make use of collectMany to automatically flatten the list

Assuming your parsed json is in a variable json, you can simply do:

json.items.collectMany { it.id }
  • Related