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

后端 未结 1 894
孤城傲影
孤城傲影 2021-01-22 10:50

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

{
  \"location\": {
    \"name\": \"London\",
    \"region\": \"City of London, Greater London\",
    \"c         


        
相关标签:
1条回答
  • 2021-01-22 11:32

    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"
      }
    ]
    
    0 讨论(0)
提交回复
热议问题