karate

karate fetch response of json using variable


In my json response, there is a date field which changes as per the day.

Here is my json:

{
    "data": {
        "0000164": {
            "2019-04-03": {
                "VALUE": 26
            }
        }
    },
    "status": 200
}

to fetch data from json, I am using the command: $.data.0000164.2019-04-03.OAK.

But I want to generalise the case. I have the date saved in a variable

Example:

* def date = '2019-04-03'
* def hotel = '0000164'

I want to fetch response by replacing hotel and date field with these values

$.data.hotel.date.OAK

Solution

  • You need to use jsonPath : https://stackoverflow.com/a/50855425/10791639

    * def date = '2019-04-03'
    * def hotel = '0000164'
    * def answer = karate.jsonPath(response, "$.data." + hotel + "." + date + ".OAK")