我试图弄清楚如何设置required我的json-schema对象数组.必需属性在对象上工作正常,而不是数组.
这是我的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
}
Run Code Online (Sandbox Code Playgroud)
这是我发送的json数组.json验证应该失败,因为我没有在这些项目中传递描述.
"items": [
{
"item_id": 1,
"quantity": 3,
"price": 30,
"title": "item1 new name"
},
{
"item_id": 1,
"quantity": 16,
"price": 30,
"title": "Test Two"
}
]
Run Code Online (Sandbox Code Playgroud)
the*_*eon 21
我通过将数组元素的模式部分嵌套在具有名称的对象中来使用此验证器来使用它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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
JSON:
{
"items":[
{
"item_id":1,
"quantity":3,
"price":30,
"title":"item1 new name"
},
{
"item_id":1,
"quantity":16,
"price":30,
"title":"Test Two"
}
]
}
Run Code Online (Sandbox Code Playgroud)
输出有两个关于缺少描述字段的错误:
[ {
"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" ]
} ]
Run Code Online (Sandbox Code Playgroud)
尝试将上述内容粘贴到此处以查看生成的相同输出.
也许你的验证器只支持JSONSchema v3?
requiredv3和v4之间的方式有所改变:
required是一个布尔值:http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7required是一个字符串数组(如示例所示):http://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.4.3小智 6
我意识到这是一个老线程,但由于这个问题是从jsonschema.net链接的,我认为值得在...
原始示例的问题在于您为"数组"类型声明"属性",而不是为数组声明"items",然后声明填充数组的"对象"类型(带有"属性") .这是原始架构代码段的修订版本:
"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
}
}
Run Code Online (Sandbox Code Playgroud)
我建议不要使用术语"items"作为数组的名称,以避免混淆,但没有什么能阻止你这样做......
| 归档时间: |
|
| 查看次数: |
34077 次 |
| 最近记录: |