Dhamo
Dhamo

Reputation: 1251

Karate - get a value that starts with a char and appears from last from json response

I am trying to get the value 'F20210518060000' which exist in this json

[{
    "name": "F20210518000000",
    "timestamp": "2021-05-18T00:00:00Z",
    "forecast_from": "2021-05-18T00:00:00Z",
    "forecast_to": "2021-05-27T00:00:00Z"
},
{
    "name": "T20210518000000",
    "timestamp": "2021-05-18T00:00:00Z",
    "forecast_from": "2021-05-18T00:00:00Z",
    "forecast_to": "2021-05-18T06:00:00Z"
},
{
    "name": "T20210518060000",
    "timestamp": "2021-05-18T06:00:00Z",
    "forecast_from": "2021-05-18T06:00:00Z",
    "forecast_to": "2021-05-18T12:00:00Z"
},
{
    "name": "F20210518060000",
    "timestamp": "2021-05-18T06:00:00Z",
    "forecast_from": "2021-05-18T06:00:00Z",
    "forecast_to": "2021-05-27T06:00:00Z"
},
{
    "name": "T20210518120000",
    "timestamp": "2021-05-18T12:00:00Z",
    "forecast_from": "2021-05-18T12:00:00Z",
    "forecast_to": "2021-05-18T18:00:00Z"
},
{
    "name": "T20210518180000",
    "timestamp": "2021-05-18T18:00:00Z",
    "forecast_from": "2021-05-18T18:00:00Z",
    "forecast_to": "2021-05-19T00:00:00Z"
}]

Condition: Get the last item in the JSON starts with 'F'

My code so far: Tried different ways but yet to get the desired response.

enter image description here Output:

14:10:23.013 [pool-1-thread-1] INFO  com.intuit.karate - [print] [
  "F20210517180000",
  "T20210517180000"]

14:10:23.018 [pool-1-thread-1] INFO  com.intuit.karate - [print] 2021-05-18T12:00:00Z

Any hint on how to go further?

Upvotes: 1

Views: 245

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

Here you go:

* def temp = null;
* def fun = function(x){ if (x.name.startsWith('F')) karate.set('temp', x.name) }
* karate.forEach(response, fun)
* match temp == 'F20210518060000'

Sometimes it is better to avoid JsonPath, read this: https://github.com/intuit/karate#json-transforms

Upvotes: 1

Related Questions