如何制作 jsonschema 以便它验证数组中的所有对象?

How do I make a jsonschema so that it validates all objects in array?

我正在尝试使用 json-schema 验证 JSON 输入,但它无法正常工作。

我有以下输入 JSON(部分):

[
  {
    "admin_state": "disabled"
  },
  {
    "state": "disabled"
  }
]

以及以下 json-schema(也是其中的一部分):

{
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "admin_state": {
          "type": "string",
          "default": "enabled",
          "enum": [
            "disabled",
            "enabled"
          ]
        }
      },
      "additionalProperties": false
    }
  ],
  "minItems": 1
}

我希望验证失败,因为 "state" 属性 不应该被允许(感谢 "additionalProperties": false选项)

但是,我可以 add/change 数组中第二项中的任何内容,验证总是成功的。当我更改第一项中的任何内容时,验证失败(如预期的那样)。

我错过了什么?

感谢您的帮助!

JSON 架构草案 7 个州...

If "items" is a schema, validation succeeds if all elements in the array successfully validate against that schema.

If "items" is an array of schemas, validation succeeds if each element of the instance validates against the schema at the same position, if any.

在您的架构中,items 是一个数组,这意味着您仅将该数组中的子方案应用于实例数组的第一个元素。只需从 items 中删除方括号,您的子模式将适用于实例中的所有项目。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "admin_state": {
        "type": "string",
        "default": "enabled",
        "enum": [
          "disabled",
          "enabled"
        ]
      }
    },
    "additionalProperties": false
  },
  "minItems": 1
}