相对较新的JSON模式(草案07)添加了if,then和else关键字。我无法弄清楚如何正确使用这些新关键词。到目前为止,这是我的JSON模式:
{
"type": "object",
"properties": {
"foo": {
"type": "string"
},
"bar": {
"type": "string"
}
},
"if": {
"properties": {
"foo": {
"enum": [
"bar"
]
}
}
},
"then": {
"required": [
"bar"
]
}
}
Run Code Online (Sandbox Code Playgroud)
如果“ foo”属性等于“ bar”,则需要“ bar”属性。这按预期工作。
但是,如果“ foo”属性不存在或输入为空,那么我什么都不想要。如何做到这一点?
empty input {}.
Run Code Online (Sandbox Code Playgroud)
发现的错误:
对象:条缺少必需的属性。架构路径:#/ then / required
我使用在线验证工具:
的if关键字的装置,如果所述值模式的结果通过了验证,则应用then模式,否则应用的else架构。
您的模式无效,因为您需要"foo"在if模式中进行要求,否则,空的JSON实例将通过对if模式的验证,因此将应用require 的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
}
Run Code Online (Sandbox Code Playgroud)