JSON schema中的`additionalProperties`规则未应用于嵌套级别属性。

3

我有一个 JSON 模式,其中 additionalProperties 规则设置为 false

该模式与 IT 技术相关。
{
  "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模式解析器/验证器能够通过验证,我正在使用的JSON模式解析器com.github.fge.jsonschema.main.JsonSchema虽然在模式中没有metadata/d并且将additionalProperties设置为false,但仍然通过了验证。
这非常具有误导性,有人可以指导我正确的方向吗? additionalProperties JSON模式定义仅适用于顶级字段而不是任何嵌套级别字段吗?
1个回答

5

additionalProperties JSON schema定义只适用于顶层字段,而不适用于任何嵌套级别的字段吗?

不是的,只要它在描述对象的模式中,您就可以将其放在需要的任何级别。在您的情况下,您只是把它放错了地方。这应该可以解决:

{
  "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并将模式组合在一起使其更加简洁。

1
谢谢您的快速回复,那么如果我有10个嵌套层,是不是意味着我需要在每一层都添加"additionalProperties": false,并且对所有"type": "object"的定义都要这样做? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接