Karate 使用空手道从JSON响应中的数组中获取最大值
我将以下Json作为API调用的响应Karate 使用空手道从JSON响应中的数组中获取最大值,karate,Karate,我将以下Json作为API调用的响应 { "location": { "name": "London", "region": "City of London, Greater London", "country": "United Kingdom", "lat": 51.52, "lon": -0.11, "tz_id": "Europe/London", "localtime_epoch": 1583594426, "loca
{
"location": {
"name": "London",
"region": "City of London, Greater London",
"country": "United Kingdom",
"lat": 51.52,
"lon": -0.11,
"tz_id": "Europe/London",
"localtime_epoch": 1583594426,
"localtime": "2020-03-07 15:20"
},
"forecast": {
"forecastday": [
{
"date": "2020-03-03",
"day": {
"maxtemp_c": 9,
"mintemp_c": 4
}
},
{
"date": "2020-03-04",
"day": {
"maxtemp_c": 8,
"mintemp_c": 4.1
}
},
{
"date": "2020-03-05",
"day": {
"maxtemp_c": 7,
"mintemp_c": 5.6
}
}
]
}
}
我想知道哪一天的气温是这三天中最高的
当我检查js函数中的temperature元素时,我目前的做法感觉效率低下,如下所示
* def hottest =
"""
function(array) {
var greatest;
var indexOfGreatest;
for (var i = 0; i < array.length; i++) {
if (!greatest || array[i].day.maxtemp_c > greatest) {
greatest = array[i].day.maxtemp_c;
indexOfGreatest = i;
}
}
return indexOfGreatest;
}
"""
* def index = call hottest response.forecast.forecastday
* def hottestdate = response.forecast.forecastday[index].date
* print hottestdate
*def horst=
"""
函数(数组){
var最大;
var指数化;
对于(var i=0;imaxist){
最大=数组[i].day.maxtemp\u c;
indexOfGreatest=i;
}
}
返回indexOfGreatest;
}
"""
*def index=呼叫最热响应.forecast.forecastday
*def hottestdate=response.forecast.forecastday[index].date
*打印hottestdate
有了这个,我得到了正确的结果,但是有人能建议一个更好的方法吗?空手道的最佳实践是根本不使用JS进行循环。它会产生更清晰、可读性更强的代码:
* def fun = function(x){ return { max: x.day.maxtemp_c, date: x.date } }
* def list = karate.map(response.forecast.forecastday, fun)
* def max = 0
* def index = 0
* def finder =
"""
function(x, i) {
var max = karate.get('max');
if (x.max > max) {
karate.set('max', x.max);
karate.set('index', i);
}
}
"""
* karate.forEach(list, finder)
* print 'found at index', index
* print 'item:', list[index]
请注意,重新塑造给定JSON是多么容易,这里的list
结果是:
[
{
"max": 9,
"date": "2020-03-03"
},
{
"max": 8,
"date": "2020-03-04"
},
{
"max": 7,
"date": "2020-03-05"
}
]