您好,我是 groovy 和 API 自动化的新手。我有以下 Json,我想添加断言来根据序列号检查周期开始日期和周期结束日期。
{
"status" : "success",
"locale" : "",
"data" : {
"periods" : [
{
"payCycleId" : "custompayperiod",
"sequence" : 1,
"cycleStartDate" : "2018-10-01",
"cycleEndDate" : "2018-10-08"
},
{
"payCycleId" : "custompayperiod",
"sequence" : 2,
"cycleStartDate" : "2018-10-09",
"cycleEndDate" : "2018-10-16"
}
]
}
}
如何检查序列 1 CycleStartDate 是否为 2018-10-01
最佳答案
Groovy 提供 JsonSlurper
使解析 JSON 文档更容易的类。考虑以下将 JSON 文档读取为 String
的示例(它也支持不同的初始化方法):
import groovy.json.JsonSlurper
def inputJson = '''{
"status" : "success",
"locale" : "",
"data" : {
"periods" : [
{
"payCycleId" : "custompayperiod",
"sequence" : 1,
"cycleStartDate" : "2018-10-01",
"cycleEndDate" : "2018-10-08"
},
{
"payCycleId" : "custompayperiod",
"sequence" : 2,
"cycleStartDate" : "2018-10-09",
"cycleEndDate" : "2018-10-16"
}
]
}
}'''
def json = new JsonSlurper().parseText(inputJson)
assert json.data.periods.find { it.sequence == 1 }.cycleStartDate == '2018-10-01'
加载 JSON 文档后,您可以通过访问嵌套字段来提取数据。例如,json.data.periods
使您可以访问存储在 JSON 文档中的数组。然后,find { it.sequence == 1 }
方法从该数组中返回一个节点,其中 sequence
字段等于 1
。最后,您可以提取cycleStartDate
并将其与预期日期进行比较。
You can find more useful examples in Groovy's official documentation.
关于groovy - 如何使用groovy脚本从Json获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824137/