我正在编写一个简单的 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
}
删除我用 <--
添加的评论复制到您的代码时,添加以指向有更改的地方。
请注意,我确实不明白为什么验证器没有针对“格式错误”的架构给出错误,但可能只是因为它看到了您将其定义为附加属性的定义,不完全确定.
关于arrays - minItems 似乎无法在 JSON 模式中正确验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29915939/