How to use if condition in Karate
Asked Answered
P

2

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

Pocky answered 2/10, 2017 at 12:7 Comment(1)
Did you check github.com/intuit/karate#contains-short-cutsSchwenk
L
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
Lozano answered 2/10, 2017 at 14:49 Comment(0)
P
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
Pocky answered 2/10, 2017 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.