我正在尝试弄清楚如何在我的json-schema对象数组上设置required。required属性只适用于对象,而不适用于数组。
下面是我的json模式的items部分:
"items": {
"type": "array",
"properties": {
"item_id": {"type" : "number"},
"quantity": {"type": "number"},
"price": {"type" : "decimal"},
"title": {"type": "string"},
"description": {"type": "string"}
},
"required": ["item_id","quantity","price","title","description"],
"additionalProperties" : false
}这是我发送过来的json数组。json验证应该失败,因为我没有在这些项中传递描述。
"items": [
{
"item_id": 1,
"quantity": 3,
"price": 30,
"title": "item1 new name"
},
{
"item_id": 1,
"quantity": 16,
"price": 30,
"title": "Test Two"
}
]发布于 2013-07-30 15:25:55
我使用this validator将数组元素的模式部分嵌套到名为items的对象中,从而使其正常工作。该模式现在有两个嵌套的items字段,但这是因为其中一个字段是JSONSchema中的关键字,而另一个字段实际上有一个名为items的字段
JSONSchema:
{
"type":"object",
"properties":{
"items":{
"type":"array",
"items":{
"properties":{
"item_id":{
"type":"number"
},
"quantity":{
"type":"number"
},
"price":{
"type":"number"
},
"title":{
"type":"string"
},
"description":{
"type":"string"
}
},
"required":[
"item_id",
"quantity",
"price",
"title",
"description"
],
"additionalProperties":false
}
}
}
}JSON:
{
"items":[
{
"item_id":1,
"quantity":3,
"price":30,
"title":"item1 new name"
},
{
"item_id":1,
"quantity":16,
"price":30,
"title":"Test Two"
}
]
}输出中有两个关于缺少描述字段的错误:
[ {
"level" : "error",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/items/items"
},
"instance" : {
"pointer" : "/items/0"
},
"domain" : "validation",
"keyword" : "required",
"message" : "missing required property(ies)",
"required" : [ "description", "item_id", "price", "quantity", "title" ],
"missing" : [ "description" ]
}, {
"level" : "error",
"schema" : {
"loadingURI" : "#",
"pointer" : "/properties/items/items"
},
"instance" : {
"pointer" : "/items/1"
},
"domain" : "validation",
"keyword" : "required",
"message" : "missing required property(ies)",
"required" : [ "description", "item_id", "price", "quantity", "title" ],
"missing" : [ "description" ]
} ]尝试将上述内容粘贴到here中,以查看生成的相同输出。
发布于 2013-07-30 04:29:49
也许你的验证器只支持JSONSchema v3?
在v3和v4之间,required的工作方式发生了变化:
https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-03#section-5.7
required是一个布尔值:https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#section-5.4.3
v4 required是一个字符串数组(如您的示例中所示):
发布于 2016-07-16 09:14:13
我知道这是一个老帖子,但由于这个问题是从jsonschema.net链接的,我认为它可能是值得的……
原始示例的问题在于,您为" array“类型声明了"properties”,而不是为数组声明了“item”,然后声明了一个填充数组的"object“类型(具有"properties")。以下是原始模式片段的修订版:
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"item_id": {"type" : "number"},
"quantity": {"type": "number"},
"price": {"type" : "decimal"},
"title": {"type": "string"},
"description": {"type": "string"}
},
"required": ["item_id","quantity","price","title","description"],
"additionalProperties" : false
}
}我建议不要使用术语"items“作为数组的名称,以避免混淆,但没有什么可以阻止您这样做……
https://stackoverflow.com/questions/17931874
复制相似问题