我一直试图让我的JSON架构正确。我有一个boolean
属性,我必须根据该属性确定所需的属性。下面是我的JSON
示例,我希望item3
不存在验证。
{
"item1": true,
"item2": "ABC"
}
这是我希望验证通过的JSON
{
"item1": true,
"item2": "ABC",
"item3": {
"subItem1": "ABC",
"subItem2": "BAC"
}
}
类似地,如果item1
是false
,则验证应该通过上述两个JSON。
我的JSON模式如下所示。
{
"definitions": {},
"type": "object",
"title": "The Root Schema",
"properties": {
"item1": {
"$id": "#/properties/item1",
"type": "boolean",
"title": "The Item1 Schema",
"default": false,
"examples": [
true
]
},
"item2": {
"$id": "#/properties/item2",
"type": "string",
"title": "The Item2 Schema",
"default": "",
"examples": [
"ABC"
],
"pattern": "^(.*)$"
},
"item3": {
"$id": "#/properties/item3",
"type": "object",
"title": "The Item3 Schema",
"required": [
"subItem1",
"subItem2"
],
"properties": {
"subItem1": {
"$id": "#/properties/item3/properties/subItem1",
"type": "string",
"title": "The Subitem1 Schema",
"default": "",
"examples": [
"AAA"
],
"pattern": "^(.*)$"
},
"subItem2": {
"$id": "#/properties/item3/properties/subItem2",
"type": "string",
"title": "The Subitem2 Schema",
"default": "",
"examples": [
"BAC"
],
"pattern": "^(.*)$"
}
}
}
},
"required": ["item1"],
"allOf": [{
"if": {
"properties": {
"item1": {
"enum": [
true
]
}
}
},
"then": {
"required": [
"item2",
"item3"
]
},
"else": {
"required": [
"item2"
]
}
}]
}
我的验证总是失败。
如果item1
为真,则应该要求使用subItem2
。如果item1
为假,则不需要item3
,但仍应验证是否包括在内。
您的if
/ then
/ else
块在验证方面正常工作。
您提供的示例JSON,您希望通过,失败,因为您要求item3
具有subItem1
和subItem2
的属性,但事实并非如此。
现在,您已经更新了应该传递给包含item3
和subItem1
的subItem2
的示例JSON,验证将通过您提供的架构传递。
另外,你想要,如果我理解正确:
如果item1为true,则应该需要subItem2。如果item1为false,则不需要item3,但仍应验证是否包含。
将需要subItem3
的架构从item3
移动到then
子句。如果你的subItem3
架构成功验证(if
是item1
),这将使true
只是“必需”
{
"definitions": {},
"type": "object",
"title": "The Root Schema",
"properties": {
"item1": {
"$id": "#/properties/item1",
"type": "boolean",
"title": "The Item1 Schema",
"default": false,
"examples": [
true
]
},
"item2": {
"$id": "#/properties/item2",
"type": "string",
"title": "The Item2 Schema",
"default": "",
"examples": [
"ABC"
],
"pattern": "^(.*)$"
},
"item3": {
"$id": "#/properties/item3",
"type": "object",
"title": "The Item3 Schema",
"required": [
"subItem1"
],
"properties": {
"subItem1": {
"$id": "#/properties/item3/properties/subItem1",
"type": "string",
"title": "The Subitem1 Schema",
"default": "",
"examples": [
"AAA"
],
"pattern": "^(.*)$"
},
"subItem2": {
"$id": "#/properties/item3/properties/subItem2",
"type": "string",
"title": "The Subitem2 Schema",
"default": "",
"examples": [
"BAC"
],
"pattern": "^(.*)$"
}
}
}
},
"required": [
"item1"
],
"allOf": [
{
"if": {
"properties": {
"item1": {
"enum": [
true
]
}
}
},
"then": {
"required": [
"item2",
"item3"
],
"properties": {
"item3": {
"required": [
"subItem2"
]
}
}
},
"else": {
"required": [
"item2"
]
}
}
]
}