当响应是随机顺序的 JSON 对象数组时,如何在 KarateAPI 中验证响应对象
我有以下回复:
{
"success":[
{
"id":"123",
"value" :"abc"
},
{
"id":"456",
"value" :"xyz"
}
}
我想验证该值是否为abc";对于 ID123"在我的回复中.
I would want to verify the value is "abc" for the id "123" in my response.
如果我的响应中 JSON 对象的顺序得到保证,我会使用以下方法进行验证:
If the order of the JSON objects in my response is assured , I would have valdiated using:
* match respone.success[0].value == "abc"
但是我的响应中对象的顺序是未知的.如何检查值是否为abc"?对于 ID123"
But my order of the objects in the response is unknown. How can I check if the value is "abc" for an id "123"
给你.请参阅已经解释了所有内容的文档:
Here you go. Please refer to the docs where everything is already explained:
* def found = $response.success[?(@.id=='123')]
* match found[0] contains { value: 'abc' }
提示,您可以重构 JSON 以使其更易于管理:
A tip, you can refactor the JSON to be easier to manage:
* 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/直觉/空手道#json-transforms
Again, please refer to the docs and other answers: https://github.com/intuit/karate#json-transforms