我正在尝试处理从API获得的json-s列表。
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
我必须对字段求和,并且为它想出了一个代码,但是看来它并没有修改mySum变量。
在此示例中,我仅使用了'originalEstimate'。
我尝试手动添加元素,并且可以正常工作。例如:(parseFloat(getNum(json [0] .originalEstimate)))== 16.0
getNum是一个从字符串中削减'h'的函数。
代码如下:
* def getNum = function (a) {return a.substring(0,a.length()-1)}
* text raw =
"""
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
"""
* json json = raw
* def mySum = 0
* def fn = function(x) {mySum = mySum + (parseFloat(getNum(x.originalEstimate)))}
* eval karate.forEach(json,fn)
* print mySum
我希望看到80.0是原始的估算总和,但我收到了0。而且,它运行得很好,只是不修改mySum
答案 0 :(得分:2)
是的,当您声明一个函数时,变量被锁定到声明该函数时的值。解决方案是使用karate.get()
和karate.set()
:
* def getNum = function(x){ return x.substring(0, x.length() - 1) }
* def sum = 0
* def fun = function(x){ var temp = karate.get('sum') + parseFloat(getNum(x.originalEstimate)); karate.set('sum', temp) }
* def response =
"""
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
"""
* eval karate.forEach(response, fun)
* print sum