Getting the maximum value from an array in a JSON response in Karate

房东的猫 提交于 2020-03-16 06:51:26

问题


I have the following Json as a response from a API call

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

I want to find out which date had the highest temperature amongst the 3 days.

The way I am currently doing feels inefficient as I am checking for the temperature element within my js function and it is as follows

* 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 

With this I am getting the correct result but can someone kindly suggest a better way of doing this?


回答1:


Best practice in Karate is to NOT use JS for loops at all. It results in cleaner, more readable code:

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

Note how easy it is to re-shape a given JSON, the result of list here would be:

[
  {
    "max": 9,
    "date": "2020-03-03"
  },
  {
    "max": 8,
    "date": "2020-03-04"
  },
  {
    "max": 7,
    "date": "2020-03-05"
  }
]


来源:https://stackoverflow.com/questions/60583920/getting-the-maximum-value-from-an-array-in-a-json-response-in-karate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!