使用空手道,我如何循环通过json来拾取基于json块中的另一个键的键值?



下面是我想从中提取y1的JSON响应。在得到响应之前,我知道x1,但不知道y1。所以对于特定的x键元素,我想要得到它的y值(在这个例子中是y1)。

我的json响应是这样的:

{
"result": [
{
"x": "x1",
"y": "y1"
},
{
"x": "x2",
"y": "y2"
}
]
}

下面是我在空手道尝试,但它似乎拾取空而不是:

* def y = get[0] response..result[?(@.x=='x')]

我从之前的调用中捕获x1。请让我知道我错在哪里。谢谢。

假设您已经将x1存储在先前调用的名为valX的变量中。现在你可以使用下面的代码得到y1

* def valY = karate.jsonPath(response, "$.result[?(@.x=='" + valX +"')]")[0].y

你可以读

  • https://stackoverflow.com/a/61379292/18026862
  • https://stackoverflow.com/a/52397707/18026862
  • https://github.com/karatelabs/karate jsonpath-filters

是的,对于动态JsonPath,请阅读文档:https://github.com/karatelabs/karate#jsonpath-filters

在最新版本的空手道>我还建议使用JS做这样的事情:

* def xToFind = 'x1'
* def found = response.result.find(o => o.x == xToFind)
* match found == { x: 'x1', y: 'y1' } 

最新更新