JSON 用于验证相互依赖的数组结构的架构
JSON Schema to validate interdependent array structure
我正在尝试编写具有以下结构约束的模式验证数组:
- 它只能包含值 1,2,3,4,5
- 如果数组包含 1,则它必须是唯一的条目
- 数组只能同时包含 2、3 或 4,例如[2,3] 不允许
- 5可以和2,3,4一起出现
所以有效数组是
[1],
[2],
[3],
[4],
[5],
[2,5],
[3,5],
[4,5]
我开始写一个模式如下:
{
"type": "array",
"oneOf": [
{ "items": { "enum": [1] } },
{
"anyOf": [
???
]
}
]
}
我无法使 ???
部分正常工作。有可能吗?
注意:我想避免对所有可能的数组进行硬编码,因为我必须验证更复杂的结构——这只是一个示例。此外,最佳方案是仅使用 anyOf, allOf, oneOf, not
的解决方案,避免使用 minItems
等关键字
这将通过您的所有约束。
{
"type": "array",
"anyOf": [
{ "enum": [[1]] },
{
"items": { "enum": [2, 3, 4, 5] },
"oneOf": [
{ "$ref": "#/definitions/doesnt-contain-2-3-or-4" },
{ "$ref": "#/definitions/contains-2" },
{ "$ref": "#/definitions/contains-3" },
{ "$ref": "#/definitions/contains-4" }
]
}
],
"definitions": {
"doesnt-contain-2-3-or-4": {
"items": { "not": { "enum": [2, 3, 4] } }
},
"contains-2": {
"not": {
"items": { "not": { "enum": [2] } }
}
},
"contains-3": {
"not": {
"items": { "not": { "enum": [3] } }
}
},
"contains-4": {
"not": {
"items": { "not": { "enum": [4] } }
}
}
}
}
如果您可以选择使用新的 draft-06 关键字 contains
和 const
,这实际上是一个非常干净的解决方案。有一点重复,但我认为这无济于事。
{
"type": "array",
"anyOf": [
{ "const": [1] },
{
"items": { "enum": [2, 3, 4, 5] },
"oneOf": [
{ "not": { "contains": { "enum": [2 ,3, 4] } } },
{ "contains": { "const": 2 } },
{ "contains": { "const": 3 } },
{ "contains": { "const": 4 } }
]
}
]
}
我正在尝试编写具有以下结构约束的模式验证数组:
- 它只能包含值 1,2,3,4,5
- 如果数组包含 1,则它必须是唯一的条目
- 数组只能同时包含 2、3 或 4,例如[2,3] 不允许
- 5可以和2,3,4一起出现
所以有效数组是
[1],
[2],
[3],
[4],
[5],
[2,5],
[3,5],
[4,5]
我开始写一个模式如下:
{
"type": "array",
"oneOf": [
{ "items": { "enum": [1] } },
{
"anyOf": [
???
]
}
]
}
我无法使 ???
部分正常工作。有可能吗?
注意:我想避免对所有可能的数组进行硬编码,因为我必须验证更复杂的结构——这只是一个示例。此外,最佳方案是仅使用 anyOf, allOf, oneOf, not
的解决方案,避免使用 minItems
这将通过您的所有约束。
{
"type": "array",
"anyOf": [
{ "enum": [[1]] },
{
"items": { "enum": [2, 3, 4, 5] },
"oneOf": [
{ "$ref": "#/definitions/doesnt-contain-2-3-or-4" },
{ "$ref": "#/definitions/contains-2" },
{ "$ref": "#/definitions/contains-3" },
{ "$ref": "#/definitions/contains-4" }
]
}
],
"definitions": {
"doesnt-contain-2-3-or-4": {
"items": { "not": { "enum": [2, 3, 4] } }
},
"contains-2": {
"not": {
"items": { "not": { "enum": [2] } }
}
},
"contains-3": {
"not": {
"items": { "not": { "enum": [3] } }
}
},
"contains-4": {
"not": {
"items": { "not": { "enum": [4] } }
}
}
}
}
如果您可以选择使用新的 draft-06 关键字 contains
和 const
,这实际上是一个非常干净的解决方案。有一点重复,但我认为这无济于事。
{
"type": "array",
"anyOf": [
{ "const": [1] },
{
"items": { "enum": [2, 3, 4, 5] },
"oneOf": [
{ "not": { "contains": { "enum": [2 ,3, 4] } } },
{ "contains": { "const": 2 } },
{ "contains": { "const": 3 } },
{ "contains": { "const": 4 } }
]
}
]
}