迭代复杂的Json数组,并根据JsonPath内的索引传递值 [英] Iterate over complex JsonArray and pass value based on the index inside JsonPath
本文介绍了迭代复杂的Json数组,并根据JsonPath内的索引传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试迭代数组,并且需要将数组的每一项与我从另一个Json响应创建的模板进行比较。这是我得到的样本回复。它大得多,并且数组的大小是动态的。
* def actual =
"""
{ "id": "10103",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
},
{ "id": "12394",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
},
{ "id": "74747",
"city": "xxx",
"eq": "xxx",
"noOfSqt": "20000"
}
"""
从另一个json响应中,我将ID保存在列表中。它们的顺序与&Quot;Actual&Quot;数组中的ID不同。看起来是这样的。
* def IDs = [12394, 74747, 10103]
这是我的解决方案,如果我只有大小为1的&Actual&Quot;数组,我传递的是索引0。我从ID列表中获取第一项,然后根据该ID从&Quot;Actual&Quot;数组中检索数组项。
* def i = 0 //index zero
* def index = IDs[i] //first item of the array at index 0 is 12394
* def firstObject = karate.jsonPath(actual, "$[?(@.id == '" + index + "')]")[0] //array object where id is 12394
* def city = karate.jsonPath(someOtherJson, "$.loc[?(@.newID == '" + index + "')].value")[0]
* def eq = karate.jsonPath(someOtherJson, "$.mix[?(@.newID == '" + index + "')]..value")[0]
* def noOfSqt = karate.jsonPath(someOtherJson, "$.flat[?(@.newID == '" + index + "')].value")[0]
* def expected =
"""
{
"city": "#(city)",
"eq": "#(eq)",
"noOfSqt": "#(noOfSqt)"
}
"""
* match firstObject contains expected
请帮助我迭代,这样我就可以比较数组的每一项,而不是传递i=o(索引0)。我已经检查了空手道、重复、空手道、apendTo、空手道.forEach()、JS循环,但在实现这些内容时仍然有问题。另外,我使用CONTAINS==,因为数组和模板具有不同数量的属性。
推荐答案
首先,您可以在一行中实现您想要的(JS数组映射的空手道1.0中,而不是karate.map()
):
* match actual[*].id contains IDs.map(x => x + '')
我把它作为练习留给您来弄清楚它是如何工作的。
有时完全可以使用JsonPath表达式或karate.map()
将现有的JSON转换为另一个形状。有关更多详细信息,请阅读以下内容:https://stackoverflow.com/a/53120851/143475
这篇关于迭代复杂的Json数组,并根据JsonPath内的索引传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文