在空手道中,如何参数化响应字段中字符串的一部分



我正在尝试打印基于特定参数的响应。为此,我得到了API的回应如下:

{
"ABC": {
"code": "ABC",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",     
},
"priority": "1"
},
"DEF": {
"code": "DEF",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "1",     
},
"priority": "1"
},
"GHI": {
"code": "GHI",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "2",     
},
"priority": "1"
},
"JKL": {
"code": "JKL",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",     
},
"priority": "1"
},
}

这是我用来打印特定值的功能文件

Feature: Value extraction
Background:
* def all = [ABC,DEF,GHI,JKL]

场景:提取响应值

Given url 
When method get
Then status 200
And def value = []
And eval for(var i=0;i<all.length;i++) {value.add(response['#(all[i])']["execution"]["status"]) }
And print value

我想提取状态为"0"的所有参数的值;0〃;。

print response["ABC"]["execution"]["status"]

上面的行给出了结果,但我想将["ABC"]部分参数化有什么帮助吗?我有没有其他方法可以实现这一点,或者我是否做错了什么来实现这一特定的边缘情况?

我在下面提供了一个回答多个问题的示例:

* def response =
"""
{
"ABC": {
"code": "ABC",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "0",     
},
"priority": "1"
},
"DEF": {
"code": "DEF",
"isActive": "true",
"lastUpdatedBy": "username",
"execution": {
"status": "1",     
},
"priority": "1"
}
}
"""
# get all values in root json
* def items = $.*
* def code = 'ABC'
* def found = items.filter(x => x.code == code && x.execution.status == '0')
* assert found.length == 1
# the expression on the right below is pure JS
* match found[0] == response[code]

注:

  • 如何使用json路径来简化json,也可以参考:https://stackoverflow.com/a/68811696/143475
  • 如何使用CCD_ 1 API来";查找";使用可以参数化的复杂表达式的数据,另请参见:https://github.com/karatelabs/karate#json-变换
  • 如何获取可以动态和参数化的键的值

最新更新