我正在尝试通过使用存储在名为“jsonFieldName”的变量中的值的位置从 JSON 响应中提取自行车品牌“Cannondale”
或者,我可以使用以下语法成功提取品牌价值:
def brand = json.store.bicycle.brand
但是,我想将元素的位置保留在变量中。原因是,我希望能够在 Json 响应上迭代多个断言作为我的自动化套件的一部分。
有人可以建议如何做到这一点吗?
下面是我目前将位置存储在变量中的片段。但它不起作用并且总是将品牌返回为“Null”:(谢谢。
def response = ('''{
"store": {
"book": [
{
"title": "Sword of Honour",
"category": "fiction",
"author": "Evelyn Waugh",
"@price": 12.99
},
{
"title": "Moby Dick",
"category": "fiction",
"author": "Herman Melville",
"isbn": "0-553-21311-3",
"@price": 8.99
},
{
"title": "Sayings of the Century",
"category": "reference",
"author": "Nigel Rees",
"@price": 8.95
},
{
"title": "The Lord of the Rings",
"category": "fiction",
"author": "J. R. R. Tolkien",
"isbn": "0-395-19395-8",
"@price": 22.99
}
],
"bicycle": {
"brand": "Cannondale",
"color": "red",
"price": 19.95
}
}
}''').toString()
//store location of json property I want to extract in property called jsonFieldName
def jsonFieldName = "store.bicycle.brand"
def json = new JsonSlurper().parseText (response)
//perform extraction
brand = json."${jsonFieldName}"