6

假设我有以下 Json 响应

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

那么如何提取名称为 David 的数组进行进一步验证呢?

例如我想说如果 name == David 然后保存 id

4

2 回答 2

12

干得好 :) 掌握 Json-Path 是充分利用空手道的关键!

只是为了演示,这里有另一个选项,使用get关键字从返回的数组中获取第一个元素,因为 Json-Path 通配符搜索总是返回一个数组:

* 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
于 2017-10-02T14:49:15.143 回答
4

我在 Json 表达式评估中找到了解决方案 -

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

然后我可以使用以下 -

def userId = user[0].id
于 2017-10-02T13:14:39.710 回答