我想验证一个 JSON 模式,其中嵌套 JSON 响应中的对象是可选的,但如果该对象出现,则该对象中的键也应该出现。
响应示例:-
{
"id" : "1234",
"targetPhoneNumber" : "1234",
"paid" : { //optional
"units" : "asd", //mandatory if the paid object is coming
"amount" : 12.00 //mandatory if the paid object is coming
},
"date" : "2019",
"boolean" : false,
"transactionId" : "1234"
}
我需要对这些情况进行架构检查。
1) 如果付费对象即将到来,它应该是一个 JSON 对象,并且应包含字符串单位和强制金额。 2) 如果付费对象没有到来,架构验证仍然应该通过。
最佳答案
组合'self' validation expressions和 karate.match(actual, Expected)
API 提供了一些方法来实现这一点,
这应该有效,
* def schema =
"""
{
"boolean": "#boolean",
"date": "#string",
"id": "#string",
"paid": "##object? karate.match(_,{\"amount\": \"#number\",\"units\": \"#string\"}).pass",
"targetPhoneNumber": "#string",
"transactionId": "#string"
}
"""
如果您不想内联添加子架构/如果您的子架构太大,您可以尝试此操作
* def passSchema =
"""
{
"amount": "#number",
"units": "#string"
}
"""
* def schema =
"""
{
"boolean": "#boolean",
"date": "#string",
"id": "#string",
"paid": "##object? karate.match(_,passSchema).pass",
"targetPhoneNumber": "#string",
"transactionId": "#string"
}
"""
简单的 JSON 架构:
{
"boolean": "#boolean",
"date": "#string",
"id": "#string",
"paid": "##object? karate.match(_,{\"amount\": \"#number\",\"units\": \"#string\"}).pass",
"targetPhoneNumber": "#string",
"transactionId": "#string"
}
关于Karate DSL : How to check if the JSON object is optional, 但如果该对象来自该对象内的键应该具有正确的架构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54096758/