【发布时间】:2019-09-14 09:25:30
【问题描述】:
我一直在努力让我的 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,但仍应验证是否包含。
【问题讨论】:
-
我在您的架构中看到的是,如果 item1 为真,则需要 item2 和 item3,否则,只需要 item2。这是你的意图吗?我不完全清楚你的目标是什么。您能否提供您希望成功验证的示例 JSON 以及您希望验证失败的示例 JSON?
-
我在描述中添加了一个示例 JSON。只是切换变化是从真到假。 @Relequestual
-
从您对问题的描述来看,您的
then和else似乎是错误的,但我无法判断,因为您的架构和您所说的你想要的似乎是矛盾的。因此为什么我问你是否可以提供你想要通过和失败的 JSON,因为目前还不清楚。 -
@Relequestual添加了 JSON 样本
-
您的 if/then/else 块在验证方面工作正常。您提供的希望通过的示例 JSON 失败,因为您要求
item3具有subItem1和subItem2的属性,但它没有。
标签: json jsonschema