How to use if condition in Karate

Viewed 5276

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

2 Answers

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

I found the solution in the Json expression evaluation -

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

Then I can use the following -

def userId = user[0].id
Related