【问题标题】:JSON Schema not working as expected with if/then/elseJSON Schema 无法与 if/then/else 一起按预期工作
【发布时间】: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


【解决方案1】:

您的条件句没有任何“else”子句——所以如果if 部分为假,else 将默认为true,这将导致allOf 的该分支为真。您可能想为其中的每一个添加一个"else": false

(另外,我注意到您的正则表达式没有锚定 - 例如“abc01234xyz”将匹配您的美国邮政编码模式。)

【讨论】:

    猜你喜欢
    • 2013-12-16
    • 2013-11-25
    • 2016-05-15
    • 2020-11-28
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2020-04-09
    • 2012-02-19
    相关资源
    最近更新 更多