【问题标题】:Preventing dependent property validation when the parent property does not exist当父属性不存在时阻止依赖属性验证
【发布时间】:2019-09-06 16:21:12
【问题描述】:

我是 JSON 模式的新手。我有一个属性 (property1),它依赖于另一个属性 (property2),而另一个属性 (property2) 又依赖于第三个属性 (property3)。我试图弄清楚如果 property2 不存在,如何防止架构验证 property1。我正在使用 Python jsonschema 模块进行验证。

我有一个包含三个属性的简单架构:species、otherDescription 和 otherDescriptionDetail。我要执行的规则是:

1) 如果 species = "Human",则需要 otherDescription。

2) 如果 species = "Human" and otherDescription != "None",则需要 otherDescriptionDetail。

3) 如果 species != "Human",则其他两个字段都不是必需的。

如果物种是“人类”并且 otherDescription 不存在,我的测试 JSON 正确地验证失败,但它也报告 otherDescriptionDetail 是必需属性,即使此时它不应该是因为没有 otherDescription 值可比较它反对。是否可以使用 JSON 模式实现此逻辑?

这是我的架构:

"$schema": "http://json-schema.org/draft-07/schema#",
  "$id":"http://example.com/test_schema.json",
  "title": "annotations",
  "description": "Validates file annotations",
  "type": "object",
  "properties": {
    "species": {
      "description": "Type of species",
      "anyOf": [
        {
          "const": "Human",
          "description": "Homo sapiens"
        },
        {   
          "const": "Neanderthal",
          "description": "Cave man"
        }
      ]
    },
    "otherDescription": {
      "type": "string"
    },
    "otherDescriptionDetail": {
      "type": "string"
    }
  },
  "required": [
    "species"
  ],
  "allOf": [
    {
      "if": {
        "properties": {
          "species": {
            "const": "Human"
          }
        }
      },
      "then": {
        "required": ["otherDescription"]
      }
    },
    {
      "if": {
        "allOf": [
          {
            "properties": {
              "species": {
                "const": "Human"
              },
              "otherDescription": {
                "not": {"const": "None"}
              }
            }
          }
        ]
      },
      "then": {
        "required": ["otherDescriptionDetail"]
      }
    }
  ]
}

我的测试 JSON 是:

{
  "species": "Human"
}

我想要的输出:

0: 'otherDescription' is a required property

我得到的输出:

0: 'otherDescription' is a required property
1: 'otherDescriptionDetail' is a required property

任何帮助将不胜感激。

【问题讨论】:

    标签: jsonschema


    【解决方案1】:

    您需要将otherDescription 定义为insilde allOf 的必需属性。否则即使otherDescription 不可用,allOf 块也会通过。

    "if": {
      "allOf": [
         {
           "properties": {
              "species": {
                 "const": "Human"
              },
              "otherDescription": {
                 "not": {"const": "None"}
              }
           },
           "required": ["otherDescription"]
         }
       ]
    },
    "then": {
       "required": ["otherDescriptionDetail"]
    }
    

    【讨论】:

    • 鉴于if 中只有一个架构,您无需将其包装在allOf 中。
    • schema其实比较大,因为其他部分大同小异,我只贴了一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多