我知道这里有一个类似的问题,但是并没有真正解决我的问题。简而言之,我希望我的一个字段依赖于另一个字段的值。但是对于某些值,我不要求任何字段。这是一个例子:
架构
{
"definitions": {},
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": ["red", "black", "blue"]
},
"blackQuote": {
"type": "string",
"maxLength": 11
},
"redQuote": {
"type": "string",
"maxLength": 11
}
},
"oneOf": [
{
"properties": {
"colour": {"enum": ["red"]}
},
"required": ["redQuote"]
},
{
"properties": {
"colour": {"enum": ["black"]}
},
"required": ["blackQuote"]
}
],
"required": [
"colour"
]
}
这是这样的:
最佳答案
您可以使用称为蕴含(!A或B)的 bool 逻辑概念来实现此目的。它可以像“if-then”语句一样使用。例如,“color”不是“red”或“redQuote”是必需的。每当我需要使用它时,我都会使用definitions
对其进行分解,以使其读得尽可能好。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"colour": { "enum": ["red", "black", "blue"] },
"blackQuote": { "type": "string", "maxLength": 11 },
"redQuote": { "type": "string", "maxLength": 11 }
},
"allOf": [
{ "$ref": "#/definitions/red-requires-redQuote" },
{ "$ref": "#/definitions/black-requires-blackQuote" }
],
"required": ["colour"],
"definitions": {
"red-requires-redQuote": {
"anyOf": [
{ "not": { "$ref": "#/definitions/is-red" } },
{ "required": ["redQuote"] }
]
},
"black-requires-blackQuote": {
"anyOf": [
{ "not": { "$ref": "#/definitions/is-black" } },
{ "required": ["blackQuote"] }
]
},
"is-red": {
"properties": {
"colour": { "enum": ["red"] }
}
},
"is-black": {
"properties": {
"colour": { "enum": ["black"] }
}
}
}
}