我想验证一个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)如果仍然没有付费对象,则模式验证应通过。
答案 0 :(得分:3)
结合使用'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"
}
"""
如果您不想内联添加subSchema /如果子模式太大,则可以尝试
* 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"
}
答案 1 :(得分:1)
有条件的话可以这样做:
* def outerMatcher =
"""
{
"id" : "#string",
"targetPhoneNumber" : "#string",
"paid" : "##object",
"date" : "#string",
"boolean" : "#boolean",
"transactionId" : "#string"
}
"""
* def paidMatcher =
"""
{
"units": "#string",
"amount": "#number"
}
"""
* def innerMatcher = karate.match(response.paid, "#object").pass ? paidMatcher : "#notpresent"
* match response == outerMatcher
* match response.paid == innerMatcher