迭代复杂的 JsonArray 并根据 JsonPath 中的索引传递值
Iterate over complex JsonArray and pass value based on the index inside 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 保存在列表中。它们的顺序与“实际”数组中的 ID 不同。看起来是这样。
* def IDs = [12394, 74747, 10103]
如果我只有大小为 1 的“实际”数组,我正在传递索引 0,这就是我的解决方案。我从 ID 列表中获取第一项,然后基于该项从“实际”数组中检索数组项编号.
* 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(索引为零),请帮助我进行迭代,这样我就可以比较数组中的每一项。我查看了 karate.repeat、karate.apendTo、karate.forEach()、JS 循环,但在实施这些循环时仍然遇到问题。我也使用 contains 而不是 == 因为数组和模板具有不同数量的属性。
首先,你可以在一行中实现你想要的(在空手道 1.0 中,JS 数组映射而不是 karate.map()
):
* match actual[*].id contains IDs.map(x => x + '')
我把它作为练习留给你弄清楚它是如何工作的。
有时可以使用 JsonPath 表达式或 karate.map()
将现有 JSON 转换为另一个“形状”。请阅读此内容了解更多详情:
我正在尝试遍历数组,需要将数组的每一项与我根据另一个 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 保存在列表中。它们的顺序与“实际”数组中的 ID 不同。看起来是这样。
* def IDs = [12394, 74747, 10103]
如果我只有大小为 1 的“实际”数组,我正在传递索引 0,这就是我的解决方案。我从 ID 列表中获取第一项,然后基于该项从“实际”数组中检索数组项编号.
* 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(索引为零),请帮助我进行迭代,这样我就可以比较数组中的每一项。我查看了 karate.repeat、karate.apendTo、karate.forEach()、JS 循环,但在实施这些循环时仍然遇到问题。我也使用 contains 而不是 == 因为数组和模板具有不同数量的属性。
首先,你可以在一行中实现你想要的(在空手道 1.0 中,JS 数组映射而不是 karate.map()
):
* match actual[*].id contains IDs.map(x => x + '')
我把它作为练习留给你弄清楚它是如何工作的。
有时可以使用 JsonPath 表达式或 karate.map()
将现有 JSON 转换为另一个“形状”。请阅读此内容了解更多详情: