1

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!

Kumar
  • 295
  • 1
  • 5
  • 10

1 Answers1

1

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'
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • awesome! Thank you! – Kumar Mar 04 '21 at 02:49
  • quick follow up, if I may......instead of numeric 233 in the above example, if I want to use a variable, do I use it like a javascript variable `'#(myVariable)'` or just directly as `myVariable`? Both of those ways are not working and I am wondering if I should have known a third way too.... – Kumar Mar 04 '21 at 22:35
  • I have similar issue but I have a different dynamic value appearing for nickName every time unlike how it's hard coded here that you are matching to. How do I capture such a dynamic value of nickName for that specific id? – astar May 05 '22 at 18:46
  • @astar see if this helps, else ask a new question with a clear and simple example: https://stackoverflow.com/a/50855425/143475 – Peter Thomas May 05 '22 at 18:55
  • Thanks @PeterThomas but the example you shared is slightly different that mine. Please see my original question I just posted here: [stackoverflow.com](https://stackoverflow.com/questions/72132472/using-karate-how-do-i-loop-though-a-json-to-pick-up-the-value-for-a-key-based-o) – astar May 05 '22 at 19:52
  • @PeterThomas any help greatly appreciated. thanks – astar May 05 '22 at 20:48