我编写了一个Groovy脚本,从HTTP响应图中提取城市的值,其中水果应该是变量f中获得的值,颜色应该是变量c中获得的值。假定通过某种方法正确获得了f和c的值。如果您在HTTP响应中仔细查看,则在“红色”开头有一个额外的空白,而在“黄色”结尾有一个额外的空白。水果名称中也有多余的空格。这妨碍了我的比较。如何确保比较期间忽略HTTP响应中单词开头和结尾的空格?
{
"userInformation": {
"Name": "John",
"Location": "India"
},
"details": [
{
"fruit": "Apple ",
"color": " Red",
"city": "New Delhi",
"luckyNumber": 10
},
{
"fruit": "Banana ",
"color": "yellow ",
"city": "Goa",
"luckyNumber": 12
}
]
}
这是我正在使用的代码-
def f = execution.getVariable("Fruits")
def c = execution.getVariable("Colors")
def cityName =httpResponse.json.details.find { it.fruit == f && it.color == c }?.city
答案 0 :(得分:0)
假设下面的s
是您提供的JSON代码段,然后考虑(完整示例here):
def json = new groovy.json.JsonSlurper().parseText(s)
def f = 'Apple'
def c = 'Red'
def trimCompare = { a, b ->
a.trim() == b.trim()
}
def cityName = json.details
.find { trimCompare(it.fruit,f) && trimCompare(it.color,c) }
?.city
assert 'New Delhi' == cityName