【发布时间】:2020-11-03 06:39:01
【问题描述】:
我在想出一个可以适应这些场景的架构时遇到了麻烦:
- 此字段可以有 A,和/或只有 B 或 C 之一
- 此字段只能有 A
- 此字段只能包含 B 之一或 C 之一
A、B 和 C 具有相同的架构。
基本上B和C不能同时存在。
示例场景:
// Valid
{
"exampleItem": {
"A": [{
"key": "item A",
"description": "test desc"
}],
"B": [{
"key": "item B",
"description": "test desc"
}]
}
}
// Invalid
{
"exampleItem": {
"B": [{
"key": "item B",
"description": "test desc"
}],
"C": [{
"key": "item C",
"description": "test desc"
}]
}
}
我的尝试:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"exampleItemSchema": {
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"A": {
"type": "array",
"items": {
"type": "object",
"required": [ "key", "description" ],
"properties": {
"key": {
"type": "string"
},
"description": {
"type": "string"
}
}
}
},
"B": {
"type": "array",
"items": {
"type": "object",
"required": [ "key", "description" ],
"properties": {
"key": {
"type": "string"
},
"description": {
"type": "string"
}
}
}
}
}
},
{
"type": "object",
"properties": {
"A": {
"type": "array",
"items": {
"type": "object",
"required": [ "key", "description" ],
"properties": {
"key": {
"type": "string"
},
"description": {
"type": "string"
}
}
}
},
"C": {
"type": "array",
"items": {
"type": "object",
"required": [ "key", "description" ],
"properties": {
"key": {
"type": "string"
},
"description": {
"type": "string"
}
}
}
}
}
}
]
}
}
}
我现在正在使用oneOf,但我很确定这不是我想要的。我不能使用anyOf,因为我不希望 B 和 C 同时存在,而allOf 会针对 A、B 和 C 断言。
【问题讨论】:
-
您知道 JSON Schema 中的
not关键字吗?你可以做not>required: B,C。抱歉目前在手机上。可以稍后形成答案。
标签: javascript json jsonschema json-schema-validator