我是JSON模式的新手。我有一个属性(property1)依赖于另一个属性(property2),而该属性又依赖于第三个属性(property3)。我试图弄清楚如果不存在property2,如何防止架构验证property1。我正在使用Python jsonschema模块进行验证。
我有一个具有三个属性的简单架构:种类,otherDescription和otherDescriptionDetail。我要强制执行的规则是:
1)如果物种=“人类”,则需要其他描述。
2)如果物种=“人类”且otherDescription!=“无”,则需要otherDescriptionDetail。
3)如果物种!=“人类”,则不需要其他两个字段。
如果种类为“人类”并且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
任何帮助将不胜感激。
答案 0 :(得分:1)
您需要将otherDescription
定义为必需的属性insilde allOf
。否则,即使allOf
不可用,otherDescription
块也将通过。
"if": {
"allOf": [
{
"properties": {
"species": {
"const": "Human"
},
"otherDescription": {
"not": {"const": "None"}
}
},
"required": ["otherDescription"]
}
]
},
"then": {
"required": ["otherDescriptionDetail"]
}