当父 属性 不存在时阻止从属 属性 验证

Preventing dependent property validation when the parent property does not exist

我是 JSON 模式的新手。我有一个 属性 (属性1) 依赖于另一个 属性 (属性2),而后者又依赖于第三个 属性 (属性3).如果 属性2 不存在,我想弄清楚如何防止模式验证 属性1。我正在使用 Python jsonschema 模块进行验证。

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

1) if species = "Human", otherDescription is required.

2) 如果物种 = "Human" 和 otherDescription != "None",则需要 otherDescriptionDetail。

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

如果 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

如有任何帮助,我们将不胜感激。

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

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