【问题标题】:How to validate sub-schemas based on value in parent schema如何根据父模式中的值验证子模式
【发布时间】:2021-09-21 13:20:08
【问题描述】:

我正在尝试使用 jsonschema 库验证 JSON 架构。

场景: 我需要确保如果在父对象中发送属性中的特定值,子(子模式)也应该在同一属性中获得相同的值。

JSON:->

{
"type": "object",
  "properties": {
"action": {
  "enum": [
    "get",
    "post"
  ]
},
"order": {
  "properties": {
    "id": "string",
    "action": {
      "enum": [
        "get",
        "post"
      ]
    }
  }
}},"dependentSchemas": {
"if": {
  "action": {
    "const": "get"
  }
},
"then": {
  "properties": {
    "order": {
      "properties": {
        "action": {
          "const": "get"
        }
      }
    }
  }
}
}
}

示例测试用例: 正面:

{
"action": "get",
"order": {
   "id" : "1"
   "action": "get"
      }
}

否定:

{
"action": "get",
"order": {
   "id" : "2"
   "action": "post"
      }
}

我正在使用dependentSchemas 来验证子模式:-click here

【问题讨论】:

    标签: json jsonschema json-schema-validator python-jsonschema


    【解决方案1】:

    dependentSchemas 不适用于这种情况。 dependentSchemas 在属性存在时分支,而不是它的值。您需要使用if/then 对属性的值进行分支。

    "allOf": [
      {
        "if": {
          "type": "object",
          "properties": {
            "action": { "const": "get" }
          },
          "required": ["action"]
        },
        "then": {
          "properties": {
            "order": {
              "action": { "const": "get" }
            }
          }
        }
      },
      ... Another if/then just like the first but with "post" ...
    ]
    

    注意:if 架构中必须使用 typerequired 关键字,以便在极端情况下获得良好的错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多