3

我正在尝试通过使用存储在名为“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}"
4

2 回答 2

3

new JsonSlurper().parseText(response)返回一个map,因此, search for"store.bicycle.brand"将查找变量中命名的键store.bicycle.brandjson而您想先在 the 中查找json['store'],然后在 index中查找['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'
于 2016-10-12T23:53:32.490 回答
0

问题是使用字符串访问属性;该字符串被视为属性的全名,因此您不能使用它来访问多个深度属性;换句话说,.被认为是属性名称的一部分。

一种可能的解决方法是按.字符拆分字符串并逐个访问属性:

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

jsonFieldName.split("\\.").each{json = json[it]}

assert json == 'Cannondale'
于 2016-10-12T23:53:09.973 回答