当响应是随机顺序的 JSON 对象数组时如何验证 KarateAPI 中的响应对象

How to validate response object in KarateAPI when the response is an array of JSON objects in random order

我有以下回复:

{
  "success":[
    {
      "id":"123",
      "value" :"abc"
    },
    {
      "id":"456",
      "value" :"xyz"
    }
}

我想验证我的回复中 ID“123”的值是“abc”。

如果我的响应中 JSON 对象的顺序是确定的,我会使用以下方法进行验证:

* match respone.success[0].value == "abc"

但是我在响应中的对象顺序是未知的。如何检查 ID 为“123”的值是否为“abc”

给你。请参阅已解释所有内容的文档:

* def found = $response.success[?(@.id=='123')]
* match found[0] contains { value: 'abc' }

提示,您可以重构 JSON 以更易于管理:

* def fun = function(x){ var key = x.id; var res = {}; res[key] = x.value; return res }
* def data = karate.map(response.success, fun)
* match data == [{ '123': 'abc' }, { '456': 'xyz' }]

同样,请参考文档和其他答案:https://github.com/intuit/karate#json-transforms