【发布时间】:2021-08-28 12:20:30
【问题描述】:
我有以下架构:
{
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"country": {
"default": "United States of America",
"enum": ["United States of America", "Canada", "Netherlands"]
}
},
"allOf": [
{
"if": {
"properties": { "country": { "const": "United States of America" } }
},
"then": {
"properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
}
},
{
"if": {
"properties": { "country": { "const": "Canada" } },
"required": ["country"]
},
"then": {
"properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
}
},
{
"if": {
"properties": { "country": { "const": "Netherlands" } },
"required": ["country"]
},
"then": {
"properties": { "postal_code": { "pattern": "[0-9]{4} [A-Z]{2}" } }
}
}
]
}
这是从这里复制的https://json-schema.org/understanding-json-schema/reference/conditionals.html
当我将 allOf 关键字更改为 anyOf 时,它给了我意想不到的结果。我正在使用 Ajv 进行验证。
即使有以下数据,验证也会通过:
{ country: "Canada", postal_code: "some invalid code" }
但是当我只留下一个if/then 声明(针对加拿大)时,它会按预期失败。
在我将关键字更改为oneOf 的情况下,它会失败,因为有多个传递模式。
为什么会这样?
【问题讨论】:
-
你尝试过其他验证器吗?或者,也许您可以在 Ajv 项目存储库的 GH 问题中提问。
标签: json validation jsonschema ajv