Arrays 迭代复杂的JsonArray并基于JsonPath内的索引传递值

Arrays 迭代复杂的JsonArray并基于JsonPath内的索引传递值,arrays,loops,iterator,karate,Arrays,Loops,Iterator,Karate,我试图迭代数组,需要将数组的每个项与我从另一个Json响应创建的模板进行比较。这是我得到的示例响应。它更大,阵列的大小也是动态的 * def actual = """ { "id": "10103", "city": "xxx", "eq": "xxx", "noOfSqt": &q

我试图迭代数组,需要将数组的每个项与我从另一个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。我从IDs列表中获取第一项,然后根据该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==代替,因为数组和模板具有不同数量的属性。

首先,您可以在一行中实现所需的内容(对于JS数组映射,使用空手道1.0代替空手道.map()):

我把它作为一个练习留给你去弄清楚它是如何工作的


有时,使用JsonPath表达式或
karate.map()
将现有JSON转换为另一个“形状”是完全可以的。请阅读此文以了解更多详细信息:

您能就我尝试的不同方法提供建议吗?
* match actual[*].id contains IDs.map(x => x + '')