在空手道中使用 If 条件来提取值

Use If condition in Karate to extract values

我有以下 JSON 回复 -

    {
        "type": "StudentSchema",
        "version": 1,
        "students": [
            {
                id: 1,
                name: "John",
                roll: "1234"
            },
            {
                id: 2,
                name: "David",
                roll: "4434"
            }
        ]
}

那我怎样才能在空手道中提取名为 John 的数组来做进一步的验证呢? 例如我想说 if name == John 然后保存 id

我在下面尝试但它似乎不起作用 -

* def userId =  get[0] response $[?(@students.name == 'John')].id
* match userId == 2

假设您的JSON是

MyJson =  {
    "type": "StudentSchema",
    "version": 1,
    "students": [
        {
            id: 1,
            name: "John",
            roll: "1234"
        },
        {
            id: 2,
            name: "David",
            roll: "4434"
        }
    ]
}

现在,如果您想获取名为 john 的学生的 ID,您可以使用 JSON 路径

获取它
* def JSONpath = '$..students[?(@.name=='John')].id'
* def userId = karate.jsonPath(MyJson,JSONpath)

它会给你一个满足 json 路径条件的 ID 数组,你可以从中进行断言。