首页 > 解决方案 > 在空手道的 JSON 响应中从数组中获取最大值

问题描述

我有以下 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,
    "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
        }
      }
    ]
  }
}

我想找出这 3 天中哪个日期的温度最高。

我目前正在做的方式感觉效率低下,因为我正在检查我的 js 函数中的温度元素,如下所示

* 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 

有了这个,我得到了正确的结果,但是有人可以建议一个更好的方法吗?

标签: karate

解决方案


空手道的最佳实践是根本不使用 JS for 循环。它会产生更清晰、更易读的代码:

* 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"
  }
]

推荐阅读