我试图找出如何在我的json-schema对象数组上设置required
。 required
属性可以在一个对象上运行,而不是一个数组。
以下是我的json架构的项目部分:
"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"
}
]
答案 0 :(得分:21)
我使用this validator通过将数组元素的模式部分嵌套在名为items
的对象中来使其工作。该模式现在有两个嵌套的items
字段,但这是因为一个是JSONSchema中的关键字,另一个是因为您的JSON实际上有一个名为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以查看生成的相同输出。
答案 1 :(得分:6)
也许你的验证器只支持JSONSchema v3?
required
的工作方式在v3和v4之间发生了变化:
required
是一个布尔值:http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7 required
是一个字符串数组(如示例所示):http://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.4.3 答案 2 :(得分:6)
我意识到这是一个旧线程,但由于这个问题是从jsonschema.net链接的,所以我认为值得一试... ...
您的原始示例的问题在于您声明“数组”类型的“属性”,而不是声明数组的“项目”,然后声明“对象”类型(带有“属性”)填充数组。这是原始架构代码段的修订版本:
"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”作为数组的名称,以避免混淆,但没有什么可以阻止你这样做......