JSON Schema (draft-07) 的一个相对较新的补充添加了 if、then 和 else 关键字。我不知道如何正确使用这些新关键词。到目前为止,这是我的 JSON 架构:
{
"type": "object",
"properties": {
"foo": {
"type": "string"
},
"bar": {
"type": "string"
}
},
"if": {
"properties": {
"foo": {
"enum": [
"bar"
]
}
}
},
"then": {
"required": [
"bar"
]
}
}
如果“foo”属性等于“bar”,则需要“bar”属性。这按预期工作。
但是,如果“foo”属性不存在或输入为空,那么我什么都不想要。如何实现这一目标?
empty input {}.
发现错误:
object: bar 中缺少必需的属性。
架构路径:#/then/required
我使用在线验证工具:
https://www.jsonschemavalidator.net/
最佳答案
if
关键字表示,如果值模式的结果通过验证,则应用 then
模式,否则应用 else
架构。
您的架构无效,因为您需要要求 "foo"
在您的 if
模式,否则一个空的 JSON 实例将通过 if
的验证模式,因此应用 then
架构,需要 "bar"
.
二、你要"propertyNames":false
,这可以防止在架构中包含任何键,这与您要设置 "else": false
不同。这会使任何事情总是无法通过验证。
{
"type": "object",
"properties": {
"foo": {
"type": "string"
},
"bar": {
"type": "string"
}
},
"if": {
"properties": {
"foo": {
"enum": [
"bar"
]
}
},
"required": [
"foo"
]
},
"then": {
"required": [
"bar"
]
},
"else": false
}
关于jsonschema - 如何在 json 模式中使用 `If` `then` `else` 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539586/