JSON 架构中的“additionalProperties”规则不适用于嵌套级别的属性

`additionalProperties` rule in JSON schema is not applied to nested level properties

所以我有一个 JSON 模式,其中 additionalProperties 规则设置为 false 类似。

{
  "type": "object",
  "properties": {
    "metadata": {
      "type": "object",
      "properties": {
        "a": {
          "type": "string"
        },
        "b": {
          "type": "string"
        },
        "c": {
          "type": "string"
        }
      }
    },
    "street_type": {
      "type": "string",
      "enum": [
        "Street",
        "Avenue",
        "Boulevard"
      ]
    }
  },
  "additionalProperties": false
}

和像

这样的有效载荷
{
  "metadata": {
    "a": "aa",
    "b": "bb",
    "c": "cc",
    "d": "dd"
  }
}

如果我希望我的 JSON 模式 parser/validator 通过验证,我正在使用 com.github.fge.jsonschema.main.JsonSchema 的 JSON 模式解析器通过验证,尽管 metadata/d 是不存在于 additionalProperties 设置为 false

的架构中

这是非常误导的,谁能给我指明正确的方向。

additionalProperties JSON 架构定义是否仅适用于顶级字段而不适用于任何嵌套级别字段?

Is the additionalProperties JSON schema definition only applies to top-level fields and not to any nested level fields?

不,只要它在描述对象的架构中,您就应该能够将它放在您需要的任何级别。在你的情况下,你只是把它放在错误的地方。这应该有效:

{
  "type": "object",
  "properties": {
    "metadata": {
      "type": "object",
      "properties": {
        "a": {
          "type": "string"
        },
        "b": {
          "type": "string"
        },
        "c": {
          "type": "string"
        }
      },
      "additionalProperties": false
    },
    "street_type": {
      "type": "string",
      "enum": [
        "Street",
        "Avenue",
        "Boulevard"
      ]
    }
  }
}

假设您想按原样验证以下对象:

{
  a: {
    b: {
      c: {
        d: 42
      }
    }
  }
}

它的一个有效模式是:

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "a": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "b": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "c": {
              "type": "object",
              "additionalProperties": false,
              "properties": {
                "d": {
                  "const": 42
                }
              }
            }
          }
        }
      }
    }
  }
}

上面的架构非常冗长,但此处仅供说明之用。您应该能够通过使用 $ref 并将模式组合在一起使其更加简洁。