gpt4 book ai didi

json - 如何使用变量使用 Groovy 从 JSON 响应中提取值?

转载 作者:行者123 更新时间:2023-12-01 05:26:29 33 4
gpt4 key购买 nike

我正在尝试使用存储在名为“jsonFieldName”的变量中的值的位置从 JSON 响应中提取自行车品牌“Cannondale”

或者,我可以使用以下语法成功提取品牌值(value):

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}"

最佳答案

new JsonSlurper().parseText(response) 返回 map ,因此,搜索 "store.bicycle.brand" 将在 json 变量中查找名为 store.bicycle.brand 的键,同时您希望首先查看 json['store'],然后查看索引 ['bicycle'],依此类推。

我使用了一个inject 策略来做你想做的事:

def response = '''{
"store": {
"bicycle": {
"brand": "Cannondale",
"color": "red",
"price": 19.95
}
}
}'''

def jsonFieldName = "store.bicycle.brand"
def json = new groovy.json.JsonSlurper().parseText (response)

get = { field, json2 ->
field.tokenize(".").inject(json2) { map, f -> map[f] }
}

brand = get jsonFieldName, json
assert brand == 'Cannondale'

关于json - 如何使用变量使用 Groovy 从 JSON 响应中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40009793/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com