我知道这里有一个类似的问题,但它并没有真正解决我的问题。简而言之,我希望我的一个字段依赖于另一个字段的值。但是对于某些值,我不希望需要任何字段。这是一个例子:
模式
{
"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"
]
}
这样的工作原理如下:
答案 0 :(得分:3)
您可以使用名为implication(!A或B)的布尔逻辑概念来执行此操作。它可以像" if-then"声明。例如," color"不是"红色"或" 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"] }
}
}
}
}
答案 1 :(得分:1)
如果您将所需内容的细节移到OneOf中,那么您可以非常简单地使用它,特别是如果您最终加载了其他颜色值。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": [
"red"
]
},
"redQuote": {
"type": "string",
"maxLength": 11
}
},
"required": [
"redQuote"
]
},
{
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": [
"black"
]
},
"blackQuote": {
"type": "string",
"maxLength": 11
}
},
"required": [
"blackQuote"
]
},
{
"type": "object",
"properties": {
"colour": {
"type": "string",
"enum": [
"blue"
]
}
}
}
],
"definitions": {}
}
答案 2 :(得分:1)
草案04中最简单的答案(正如Ganesh在评论中所指出的那样):
{
"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"]
},
{
"properties": {
"colour": {"enum": ["blue"]}
}
}
],
"required": [
"colour"
]
}