问题
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