How to traverse a dynamic array using karate?

删除回忆录丶 提交于 2019-12-11 06:05:30

问题


I am hitting an api -> http://127.0.0.1:5000/api/library/?book_id=2,5,13 The response of the api is:

{
    "data": {
        "2":{
                "rack": 219,
                "price": 360,
                "title": "book1"
            },
        "5":{
                "rack": 309,
                "price": 230,
                "title": "book2"
            },
        "13":{
                "rack": 112,
                "price": 200,
                "title": "book3"
            }
    },
    "status_code": 200
}

the keys 2,5,13 are variable depending on the api param.

I wrote the following code=>

Feature: Verify Library API
    Scenario: Verify book prices 
        * def id1 = 2 
        * def id2 = 5 
        * def id3 = 13 
        Given url 'http://127.0.0.1:5000/api/library/?book_id='+ id1 +',' + id2 + ',' + id3 
        When method get 
        Then status 200 
        * def id1_price = $.data.#(id1).price 
        * assert id1_price == 360

I wasn't able to get the value of the price of book1 in the variable, which resulted in the assertion failure. How do I access the price using the variable "id1"?


回答1:


When you have dynamic JsonPath expressions, use the karate.jsonPath() API. try this:

* def id1_price = karate.jsonPath(response, "$.data." + id1 + ".price")


来源:https://stackoverflow.com/questions/50854498/how-to-traverse-a-dynamic-array-using-karate

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