JSONSchema and validating sub
Given this JSON object:
{
"objects": {
"foo": {
"id": 1,
"name": "Foo"
},
"bar": {
"id": 2,
"name": "Bar"
}
}
}
This is an object containing sub objects where each sub object has the same structure - they're all the same type. Each sub-object is keyed uniquely, so it acts like a named array.
I want to validate that each object within the objects
property validates against a JSON Schema reference.
If the objects
property was an array, such as:
{
"objects": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
I could validate this with a schema definition such as:
{
"id": "my-schema",
"required": [
"objects"
],
"properties": {
"objects": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
}
}
}
}
}
This is achieved because the type
is array
, and this permits the validation of items
.
Is it possible to do something similar, but with nested objects?
Thanks!
你可以尝试这样的事情:
{
"id": "my-schema",
"type": "object",
"properties": {
"objects": {
"type": "object",
"patternProperties": {
"[a-z]+": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"id",
"name"
]
}
}
}
}
}
The above answer works for restricting the object property names to lower-case letters. If you do not need to restrict the property names, then this is simpler:
{
"id": "my-schema",
"type": "object",
"properties": {
"objects": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string }
}
},
"required": [
"id",
"name"
]
}
}
}
}
I omitted the inner "additionalProperties": false
from the above answer because I find that using that keyword causes more problems than it solves, but it is a valid use of the keyword if you want validation to fail on the inner objects if they have properties other than "name" and "id".
上一篇: jQuery / JavaScript读取本地文本文件
下一篇: JSONSchema和验证子