在jsonSchema中,您可以使用"required"属性指示已定义的字段是否为必填字段:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"header": {
"type": "object",
"properties": {
"messageName": {
"type": "string"
},
"messageVersion": {
"type": "string"
}
},
"required": [
"messageName",
"messageVersion"
]
}
},
"required": [
"header"
]
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我希望messageVersion字段不是必需的.有没有办法让这个领域的强制性有条件?
Jas*_*ers 211
根据您的情况,有几种不同的方法.我可以想到有条件地要求一个领域的四种不同方式.
该dependencies关键字是所述的一个条件变化required关键字.Foreach属性dependencies,如果该属性存在于要验证的JSON中,则与该键关联的模式也必须有效. 如果存在"foo"属性,则需要"bar"属性
{
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "string" }
},
"dependencies": {
"foo": { "required": ["bar"] }
}
}
Run Code Online (Sandbox Code Playgroud)
如果架构仅包含required关键字,则还有一个简短形式.
{
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "string" }
},
"dependencies": {
"foo": ["bar"]
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的条件取决于字段的值,则可以使用名为implication的布尔逻辑概念."A暗示B"实际上意味着,如果A为真,则B也必须为真.含义也可以表示为"!A或B". "foo"属性不等于"bar",或者"bar"属性是必需的.或者,换句话说:如果"foo"属性等于"bar",则需要"bar"属性
{
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "string" }
},
"anyOf": [
{
"not": {
"properties": {
"foo": { "const": "bar" }
},
"required": ["foo"]
}
},
{ "required": ["bar"] }
]
}
Run Code Online (Sandbox Code Playgroud)
如果"foo"不等于"bar",则#/anyOf/0匹配和验证成功.如果"foo"等于"bar",则#/anyOf/0失败并且#/anyOf/1必须对anyOf验证成功有效.
如果您的条件是基于枚举,那么它更直接. "foo"可以是"bar"或"baz".如果"foo"等于"bar",则需要"bar".如果"foo"等于"baz",则需要"baz".
{
"type": "object",
"properties": {
"foo": { "enum": ["bar", "baz"] },
"bar": { "type": "string" },
"baz": { "type": "string" }
},
"anyOf": [
{
"properties": {
"foo": { "const": "bar" }
},
"required": ["bar"]
},
{
"properties": {
"foo": { "const": "baz" }
},
"required": ["baz"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
一个相对较新除了JSON模式(草案-07)增加了if,then和else关键字. 如果"foo"属性等于"bar",则需要"bar"属性
{
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "string" }
},
"if": {
"properties": {
"foo": { "const": "bar" }
},
"required": ["foo"]
},
"then": { "required": ["bar"] }
}
Run Code Online (Sandbox Code Playgroud)
编辑12/23/2017:更新了蕴涵部分,并添加了If-Then-Else部分.
截至 2022 年,dependencies已弃用,并分为dependentRequired(参见例如本示例) 和dependentSchemas(参见例如本示例)。只需使用即可dependentRequired解决问题:
{
"type": "object",
"properties": {
"foo": { "type": "string" },
"bar": { "type": "string" }
},
"dependentRequired": {
"foo": ["bar"]
}
}
Run Code Online (Sandbox Code Playgroud)