作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我似乎找不到在枚举上应用多个 if/then 逻辑的工作方式。
anyOf
不应用条件逻辑,而是表示如果其中任何一个匹配则很好。
allOf
再次不应用条件逻辑,而是测试属性/必填字段的超集。
这是一个 JSON 架构示例:
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"title": "The Root Schema",
"required": [
"type"
],
"properties": {
"type": {
"$id": "#/properties/type",
"enum": [
"a",
"b",
"c"
],
"title": "The Type"
},
"options": {
"$id": "#/properties/options",
"type": "object",
"title": "The Options Schema",
"oneOf": [
{
"if": { "properties": { "type": { "const": "a" } }
},
"then": {
"required": [ "option1" ],
"properties": {
"option1": {
"$id": "#/properties/options/properties/option1",
"type": "boolean",
"title": "The option1 Schema"
}
}
}
},
{
"if": { "properties": { "type": { "const": "b" } }
},
"then": {
"required": [ "option2" ],
"properties": {
"option2": {
"$id": "#/properties/options/properties/option2",
"type": "boolean",
"title": "The option2 Schema"
}
}
}
},
{
"if": { "properties": { "type": { "const": "c" } }
},
"then": {
"required": [],
"properties": {}
}
}
]
}
}
}
如果您针对此 JSON 进行验证:
{
"type": "a",
"options": {
"option1": true
}
}
它失败了,因为 option2
是必需的。
如果将其更改为 anyOf
则它会成功,但如果将 JSON 更改为无效:
{
"type": "a",
"options": {
"option2": false
}
}
还是成功了。
我还没有设法嵌套 if/then/else/if/then/else 工作。
我如何检查每个 type
的属性集,而您不能将它们混合在一起?这真的可能吗,还是我应该改变我的设计。
最佳答案
首先,您可以test your schemas here .互联网上有几个这样的网站。
其次,if
/then
/else
结构被引入来代替 oneOf
枚举场景,不要与之结合。
这个子模式
"if": { "properties": { "type": { "const": "a" } } },
"then": {
"required": [ "option1" ],
"properties": {
"option1": {
"$id": "#/properties/options/properties/option1",
"type": "boolean",
"title": "The option1 Schema"
}
}
}
当 type
不是 a
时实际上并没有失败。它只是说 if type=a
,应用 then
子模式。如果 type
是 not a
,它没有说明要验证什么,所以它通过了。如果您向其中添加一个 else:false
,它会更符合您的想法,但我鼓励您以不同的方式思考它。
使用oneOf
或 if
/then
/else
,但不能同时使用.我建议更改您的子模式以使用此格式:
{
"properties": {
"type": { "const": "a" },
"option1": {
"$id": "#/properties/options/properties/option1",
"type": "boolean",
"title": "The option1 Schema"
}
},
"required": [ "option1" ],
}
这断言 option1
是必需的并且必须是 bool 值,并且 type=a
。如果 type
是 not a
,则此模式失败,这正是您想要的。
This answer更详细地描述了您需要做什么。
关于JSON Schema 嵌套 If Then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423639/
我是一名优秀的程序员,十分优秀!