使用 JSON 架构验证 numbers/booleans 的嵌套列表
Validating nested list of numbers/booleans with JSON schema
我不确定 JSON 模式是否可行,但我有类似的数据:
[1, 1, [0, 0, [true]], true]
如何验证 [0, 0, 1] 以便至少有一项为 1/true?
到目前为止,我已经设法创建了架构:
{
"type": "array",
"items": {
"$ref": "#/definitions/_items"
},
"definitions": {
"_items": {
"anyOf": [
{
"enum": [
0,
1
],
"type": "integer"
},
{
"enum": [
false,
true
],
"type": "boolean"
},
{
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/_items"
}
]
}
}
]
}
}
}
显然它确实验证了所有接受的值,但它没有考虑是否有所有、一些、一个或 none 值 1 / true。我误解了,anyOf、allOf 和 oneOf 是为此保留的...
您需要的是 contains
关键字。计划将其添加到 JSON 架构规范的下一版本中。在实现之前,你可以不用contains
,但逻辑有点复杂。我还清除了您目前所拥有的一些不必要的部分。
{
"type": "array",
"items": { "$ref": "#/definitions/_items" },
"allOf": [{ "$ref": "#/definitions/contains-1-or-true" }],
"definitions": {
"_items": {
"anyOf": [
{ "enum": [0, 1] },
{ "type": "boolean" },
{ "$ref": "#" }
]
},
"contains-1-or-true": {
"not": {
"type": "array",
"items": {
"not": { "enum": [1, true] }
}
}
}
}
}
我不确定 JSON 模式是否可行,但我有类似的数据:
[1, 1, [0, 0, [true]], true]
如何验证 [0, 0, 1] 以便至少有一项为 1/true?
到目前为止,我已经设法创建了架构:
{
"type": "array",
"items": {
"$ref": "#/definitions/_items"
},
"definitions": {
"_items": {
"anyOf": [
{
"enum": [
0,
1
],
"type": "integer"
},
{
"enum": [
false,
true
],
"type": "boolean"
},
{
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/_items"
}
]
}
}
]
}
}
}
显然它确实验证了所有接受的值,但它没有考虑是否有所有、一些、一个或 none 值 1 / true。我误解了,anyOf、allOf 和 oneOf 是为此保留的...
您需要的是 contains
关键字。计划将其添加到 JSON 架构规范的下一版本中。在实现之前,你可以不用contains
,但逻辑有点复杂。我还清除了您目前所拥有的一些不必要的部分。
{
"type": "array",
"items": { "$ref": "#/definitions/_items" },
"allOf": [{ "$ref": "#/definitions/contains-1-or-true" }],
"definitions": {
"_items": {
"anyOf": [
{ "enum": [0, 1] },
{ "type": "boolean" },
{ "$ref": "#" }
]
},
"contains-1-or-true": {
"not": {
"type": "array",
"items": {
"not": { "enum": [1, true] }
}
}
}
}
}