如何检查一个值是否与 json 响应中的另一个对应值匹配
How to check a value matches with another correpsonding value in a json response
检查 json 响应值的每个实例与脚本断言中的另一个 json 响应值匹配的最动态方法是什么?
我的意思是说我在下面有以下回复:
{
"xxx": [{
"roomInformation": [{
"xxx": xxx
}],
"totalPrice": xxx
},
{
"roomInformation": [{
xxx: xxx
}],
"totalPrice": xxx
}
]
}
我想检查第一个房价是否与第一个 totalPrice
匹配,第二个 roomPrice
与第二个 totalPrice
匹配。它必须是动态的,因为我可能会得到很多不同的实例,所以我不能简单地浏览 json 和 [0] 和 [1]。虚拟检查每个 roomPrice
与其对应的 totalPrice
.
匹配
谢谢
这是检查每个 roomPrice
是否与 totalPrice
匹配的 script assertion
。
编辑:基于 OP 提供的完整回复 here
脚本断言:
//Check if the response is not empty
assert context.response, "Response is empty or null"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def sb = new StringBuffer()
json.regions.each { region ->
region.hotels.each { hotel ->
(hotel?.totalPrice == hotel?.roomInformation[0]?.roomPrice) ?: sb.append("Room price ${hotel?.roomInformation[0]?.roomPrice} is not matching with total price ${hotel.totalPrice}")
}
}
if (sb.toString()) {
throw new Error(sb.toString())
} else { log.info 'Prices match' }
所以给定 Json 作为变量:
def jsonTxt = '''{
"hotels": [{
"roomInformation": [{
"roomPrice": 618.4
}],
"totalPrice": 618.4
},
{
"roomInformation": [{
"roomPrice": 679.79
}],
"totalPrice": 679.79
}
]
}'''
然后我们可以使用下面的脚本:
import groovy.json.*
new JsonSlurper().parseText(jsonTxt).hotels.each { hotel ->
assert hotel.roomInformation.roomPrice.sum() == hotel.totalPrice
}
如您所见,我使用 sum
将所有 roomInformation.roomPrice 值相加。在你的例子中,你只有一个价格,所以这样就可以了。而且它也涵盖了你有多个房间加在一起的情况
检查 json 响应值的每个实例与脚本断言中的另一个 json 响应值匹配的最动态方法是什么?
我的意思是说我在下面有以下回复:
{
"xxx": [{
"roomInformation": [{
"xxx": xxx
}],
"totalPrice": xxx
},
{
"roomInformation": [{
xxx: xxx
}],
"totalPrice": xxx
}
]
}
我想检查第一个房价是否与第一个 totalPrice
匹配,第二个 roomPrice
与第二个 totalPrice
匹配。它必须是动态的,因为我可能会得到很多不同的实例,所以我不能简单地浏览 json 和 [0] 和 [1]。虚拟检查每个 roomPrice
与其对应的 totalPrice
.
谢谢
这是检查每个 roomPrice
是否与 totalPrice
匹配的 script assertion
。
编辑:基于 OP 提供的完整回复 here
脚本断言:
//Check if the response is not empty
assert context.response, "Response is empty or null"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def sb = new StringBuffer()
json.regions.each { region ->
region.hotels.each { hotel ->
(hotel?.totalPrice == hotel?.roomInformation[0]?.roomPrice) ?: sb.append("Room price ${hotel?.roomInformation[0]?.roomPrice} is not matching with total price ${hotel.totalPrice}")
}
}
if (sb.toString()) {
throw new Error(sb.toString())
} else { log.info 'Prices match' }
所以给定 Json 作为变量:
def jsonTxt = '''{
"hotels": [{
"roomInformation": [{
"roomPrice": 618.4
}],
"totalPrice": 618.4
},
{
"roomInformation": [{
"roomPrice": 679.79
}],
"totalPrice": 679.79
}
]
}'''
然后我们可以使用下面的脚本:
import groovy.json.*
new JsonSlurper().parseText(jsonTxt).hotels.each { hotel ->
assert hotel.roomInformation.roomPrice.sum() == hotel.totalPrice
}
如您所见,我使用 sum
将所有 roomInformation.roomPrice 值相加。在你的例子中,你只有一个价格,所以这样就可以了。而且它也涵盖了你有多个房间加在一起的情况