6

Suppose I have the following Json response

[
    {
        id: 1,
        name: "John",
        password: "JohnsPassword54",
    },
    {
        id: 2,
        name: "David",
        password: "DavidsPassword24",
    }
]

Then how can I extract the array with name David to do further validation?

e.g. I want to say if name == David then save the id

loudmummer
  • 544
  • 3
  • 19
Amir Ghahrai
  • 618
  • 1
  • 7
  • 22

2 Answers2

12

Well done :) Mastering Json-Path is key to get the most out of Karate !

Just for the sake of demo, here is another option, using the get keyword to get the first element out of the array returned, as Json-Path wildcard searches always return an array:

* def response = 
"""
[
    {
        id: 1,
        name: "John",
        password: "JohnsPassword54"
    },
    {
        id: 2,
        name: "David",
        password: "DavidsPassword24"
    }
]
"""
* def userId = get[0] response $[?(@.name == 'David')].id
* match userId == 2
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
4

I found the solution in the Json expression evaluation -

def user = $..[?(@.name == 'David')]

Then I can use the following -

def userId = user[0].id
loudmummer
  • 544
  • 3
  • 19
Amir Ghahrai
  • 618
  • 1
  • 7
  • 22