我似乎不知道如何在 JSON 模式中实现某些目标。假设我有两个字段:status
和 quote
。
条件依赖如下:
- 如果
状态
为["Y", "N"]
,则引用
为必填< - 如果
status
是枚举中的任何其他内容,则quote
不需要 - 如果 JSON 中不存在
status
,则quote
可以是任何内容
我正在尝试使用以下架构来实现此行为:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"quote": {
"type": "string",
},
"status": {
"type": "string",
"enum": ["Y", "N", "M", "A", "S"]
}
},
"oneOf": [
{
"properties": {
"status": {"enum": ["Y", "N"]}
},
"required": [
"quote"
]
},
{
"properties": {
"status": {"enum": ["Y", "N", "M", "A", "S"]}
}
}
]
}
前两个条件按预期工作,但每当 JSON 中省略 status
字段时,验证就会失败。想要的行为是,每当 status
字段不存在时,我都可以有一个字段 quote
为任何内容。
我怎样才能实现这个目标?
更新
所以我设法实现了我最初要求的目标,但是,我现在有额外的要求。也就是说,我有一个附加字段 author
,每当 status
为 ["M", "A"]
时都需要它,否则它只是可选的。如果 status
不存在,则 quote
和 author
都可以是任何内容。我尝试过如下:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"quote": { "type": "string" },
"author": { "type": "string" },
"status": { "enum": ["Y", "N", "M", "A", "S"] }
},
"allOf": [
{ "$ref": "#/definitions/y-or-n-requires-quote" },
{ "$ref": "#/definitions/m-or-a-requires-author" }
],
"definitions": {
"y-or-n-requires-quote": {
"anyOf": [
{ "not": { "$ref": "#/definitions/status-is-y-or-n" } },
{ "required": ["quote"] }
]
},
"m-or-a-requires-author": {
"anyOf": [
{ "not": { "$ref": "#/definitions/status-is-m-or-a" } },
{ "required": ["author"] }
]
},
"status-is-y-or-n": {
"properties": {
"status": { "enum": ["Y", "N"] }
}
},
"status-is-m-or-a": {
"properties": {
"status": { "enum": ["M", "A"] }
}
}
}
}
但是,对于不存在 status
的 JSON,使用此架构不起作用。
最佳答案
请注意,draft-07 添加了“if”/“then”/“else”关键字以使条件更容易:
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-00#section-6.6
如果您的工具不支持 Draft-07,请考虑提交功能请求以更新它们:-)
关于JSON 架构 : conditional dependency,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47674950/