空手道DSL:如何检查JSON对象是否可选,但是该对象是否来自该对象内的密钥应具有正确的架构? [英] Karate DSL : How to check if the JSON object is optional, but if that object comes the keys inside that object should be of correct schema?

查看:68
本文介绍了空手道DSL:如何检查JSON对象是否可选,但是该对象是否来自该对象内的密钥应具有正确的架构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个JSON模式,其中嵌套JSON响应中的对象是可选的,但如果该对象出现,则该对象中的键也应该出现.

I want to validate a JSON schema where an object in a nested JSON response is optional but if the object comes the keys in that object should also come.

样品响应:-

{
    "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"
  }

对于这些情况,我需要进行模式检查.

I need schema checks for these cases.

1)如果付费对象即将到来,则它应该是JSON对象,并且应包含字符串形式的单位和金额(必填). 2)如果仍然没有付费对象,则模式验证应通过.

1) If the paid object is coming it should be a JSON object and should contains units as string and amount as mandatory. 2) If the paid object is not coming still the schema validation should pass.

推荐答案

结合'self '验证表达式karate.match(actual, expected) API提供了实现此目标的方法,

Combining 'self' validation expressions and karate.match(actual, expected) API gives some way to achieve this,

这应该有效,

* def schema =
"""
{
      "boolean": "#boolean",
      "date": "#string",
      "id": "#string",
      "paid": "##object? karate.match(_,{\"amount\": \"#number\",\"units\": \"#string\"}).pass",
      "targetPhoneNumber": "#string",
      "transactionId": "#string"
}
"""

如果您不想内联添加subSchema/如果子模式太大,则可以尝试

If you don't want to add your subSchema inline / if your subschema is too large you can try this

* 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"
}

这篇关于空手道DSL:如何检查JSON对象是否可选,但是该对象是否来自该对象内的密钥应具有正确的架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆