minItems 似乎无法在 JSON 模式中正确验证

minItems doesn't seem to validate correctly in JSON schema

我正在编写一个简单的 JSON 架构并使用 minItems 来验证给定数组中的项目数。我的架构如下:

{
"title": "My Schema",
"type": "object",
"properties": {
    "root": {
        "type": "array",
        "properties": {
            "id": {
                "type": "string"
            },
            "myarray": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "minItems": 4,
                "uniqueItems": true
            },
            "boolean": {
                "type": "boolean"
            }
        },
        "required": ["id","myarray","boolean"]
    }
},
"required": [
    "root"
],
"additionalProperties": false
}

现在我希望以下 JSON 验证失败,因为元素 myarray 中没有任何内容。但是当使用 this online validator 时,它通过了。是我做错了什么还是我使用的模式验证器有问题?

{
"root":[
    {
        "id":"1234567890",
        "myarray":[],
        "boolean":true
    }
]
}

我不确定为什么叫它或叫什么,但您的要求的正确模式定义应该如下所示。

根据我对 JSON 架构定义的理解,您应该在项目声明中声明数组的属性。在您的架构中,您在数组项声明之外定义属性。

在您的架构中,您有两种不同类型的数组声明:

  • 曾经只有一个对象("myarray" 对象的字符串)
  • 曾经有一个复杂的对象(下面代码中的对象名称"myComplexType")

查看两者的定义、结构以及解释方式。

更正后的架构:

{
  "title": "My Schema",
  "type": "object",
  "properties": {
    "root": {
      "type": "array",
      "items": {                  <-- Difference here - "items" instead of "properties"
        "type": "object",         <-- here - define the array items as a complex object
        "title": "myComplexType", <-- here - named for easier referencing
        "properties": {           <-- and here - now we can define the actual properties of the object
          "id": {
            "type": "string"
          },
          "myarray": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "minItems": 4,
            "uniqueItems": true
          },
          "boolean": {
            "type": "boolean"
          }
        }
      },
      "required": [
        "id",
        "myarray",
        "boolean"
      ]
    }
  },
  "required": [
    "root"
  ],
  "additionalProperties": false
}

删除我在复制到您的代码时用 <-- 添加的注释,添加是为了指出有更改的地方。

请注意,我确实不明白为什么验证器没有为 'malformed' 模式给出错误,但可能只是因为它看到了您将其定义为附加属性, 不完全确定。

您的模式唯一的问题是 root 属性 的类型应该是 object 而不是 array。因为 properties 关键字没有为数组定义,所以它被忽略了。因此,您尝试测试的模式部分被完全忽略,即使它是正确的。

这里是规范中的相关段落

Some validation keywords only apply to one or more primitive types. When the primitive type of the instance cannot be validated by a given keyword, validation for this keyword and instance SHOULD succeed.