I'm trying to come up with a json schema to validate this kind of document:
{
"rootData": {
"parent1": [
{
"parent1": [
{
"leaf1": {
"attr": "value"
}
}
]
},
{
"parent2": [
{
"leaf1": {
"attr": "value"
}
}
]
},
{
"leaf1": {
"attr": "value"
}
}
]
},
"rootInfo": {
"i1": 1
}
}
Some information:
I think I was able to figure out how to represent the hierarchical nature of the embedded parent/child part. But I don't know how to define the "rootData" top level, more precisely the choice between "parent1" or "parent2" since I can not use oneOf (I think...)
{
"$schema": "http://json-schema.org/draft-06/schema#",
"definitions": {
"parent1": {
"$id": "#parent1",
"type": "object",
"properties": {
"parent1": {
"$ref": "#node"
}
}
},
"parent2": {
"$id": "#parent2",
"type": "object",
"properties": {
"parent2": {
"$ref": "#node"
}
}
},
"leaf1": {
"$id": "#leaf1",
"type": "object",
"properties": {
"leaf1": {
"type": "object",
"properties": {
"attr": {
"type": "string"
}
},
"required": [
"attr"
]
}
}
},
"node": {
"$id": "#node",
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#parent1"
},
{
"$ref": "#parent2"
},
{
"$ref": "#leaf1"
}
]
}
}
},
"type": "object",
"properties": {
"rootData": {
"properties": {
//I tried several things here minProperties/maxProperties or oneOf ... but I actually don't know how to reuse my previous parent1 or parent2 definitions ...
}
}
}
}
Any help is welcome!
Thx
Add "required":["parent1"]
and "required":["parent2"]
constraints to your parent1 and parent2 definitions, and use oneOf
:
{
"$schema": "http://json-schema.org/draft-06/schema#",
"definitions": {
"parent1": {
"$id": "#parent1",
"type": "object",
"required": ["parent1"],
"properties": {
"parent1": {"$ref": "#node"}
}
},
// ...
},
"type": "object",
"properties": {
"rootData": {
"oneOf": [
{"$ref": "#parent1"},
{"$ref": "#parent2"}
]
}
}
}
If you tried using anyOf
and that worked, that's because your parent1
and parent2
definitions validate against each other: parent1
validates against a parent2
object, since it ignores the "parent2" property, and is valid without a "parent1" property; and vice-versa for "parent1".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.