【问题标题】:Conditional formatting not evaluated in JSONSchemaJSONSchema 中未评估条件格式
【发布时间】:2021-01-20 15:57:16
【问题描述】:

我正在尝试验证以 JSON 表示的防火墙规则。

我的 JSONSchema 的最小示例如下:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Example",
  "type": "object",
  "properties": {
    "from": {
      "$ref": "#/definitions/addressGroup"
    },
    "action": {
      "type": "string",
      "enum": ["binat", "pass"]
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "action": {
            "const": "binat"
          }
        }
      },
      "then": {
        "properties": {
          "from": {
            "format": "ip-address"
          }
        }
      }
    }
  ],
  "additionalProperties": false,
  "required": [
    "from",
    "action"
  ],
  "definitions": {
    "addressGroup": {
      "type": "string",
      "pattern": "^[ !<a-zA-Z].+$"
    }
  }
}

以下 JSON 通过验证:

{
    "action": "pass",
    "from": "test"
}

但是对于这个 JSON,“from”字段是根据 addressGroup 而不是 "format": "ip-address" 评估的。

{
    "action": "binat",
    "from": "10.1.1.1"
}

我希望触发“then”子句并根据“ip-address”定义强制格式化“from”字段。

可以在这里找到一个最小的演示:https://www.jsonschemavalidator.net/s/EsQVoaXw

我忽略了什么?

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    对于draft-07,IP 地址的指定格式为ipv4ipv6

    https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-7.3.4

    另外,format 默认什么都不做,必须启用。

    这已在 2019-09 草案中得到进一步澄清,并在 2020-12 草案中正式化为可预测的行为。

    您可能必须在您的实现中启用它。我不确定 jsonschemavalidator.net 是做什么的,因为它不是开源的。 jsonschema.dev 没有启用基于 format 的验证。

    您已正确使用if/then,但您的架构中的addressGroup 仍将被应用(不清楚这是否是您的意图)。

    根据您的评论进行更新:

    要仅在if 架构失败时应用addressGroup,您需要使用else 关键字(if / then / else 逻辑),将properties.form 移动到那里。

    {
      "if": false,
      "then": {},
      "else": {
        "properties": {
          "from": {
            "$ref": "#/definitions/addressGroup"
          }
        }
      }
    ...
    }
    

    【讨论】:

    • 我明白了。我也会检查一些其他的实现。我将如何确保不会应用 addressGroup ?理想情况下,我只希望它适用于 action != 'binat'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2019-09-23
    • 2019-03-16
    • 2015-02-22
    • 2019-06-06
    • 2017-03-04
    相关资源
    最近更新 更多