Kumar
Kumar

Reputation: 375

Trying to filter json object for a single value based on the value of other key in Karate API Test Framework

I think Karate documentation is great and I have tried to read as much as possible but this one little thing is stumping me right now. I think what I am trying to do is fairly straightforward but I am failing at it miserably. I have a JSON object here based on the example in the docs but slightly modified:

  * def cat = 
            """
            [
                {
                    name: 'Billie',
                    kittens: [
                        { id: 23, nickName: 'Bob' },
                        { id: 42, nickName: 'Wild' }
                    ]
                },
                {
                    name: 'Billie2',
                    kittens: [
                        { id: 233, nickName: 'Bob2' },
                        { id: 422, nickName: 'Wild2' }
                    ]
                }
            ]
            """

All I want to find is the value of nickName when id is 233. (In this example the answer is Bob2)

I tried this: get[0] cat.kittens[?(@.id==233)] But I think I am missing something.

What is tripping me is when there are multiple name and kittens, as opposed to a single set in the example given in the documentation website. I apologize as the answer for this is pretty straightforward, but any hint in the right direction will get greatly appreciated. Thank you!

Upvotes: 2

Views: 1241

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

You are close. When there is an array involved, typically [*] is needed.

* def temp1 = get[0] cats[*].kittens[?(@.id==233)]
* match temp1.nickName == 'Bob2'

Note that this will also work:

* def temp2 = get[0] cats..kittens[?(@.id==233)]
* match temp2.nickName == 'Bob2'

Upvotes: 2

Related Questions