JSON Schema - Recursive Schema Definition
use definitions and $ref.
You can copy and paste the following schema to this online json/schema editor and check the results.
editor screenshot:
schema code:
{
"definitions": {
"TPNode": {
"title": "TPNode",
"description": "TPNode",
"type": "object",
"properties": {
"selector": {
"type": "string",
"required": true
},
"attributes": {
"type": "array",
"items": {
"title": "Attribute",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
},
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/TPNode"
}
},
"events": {
"type": "array",
"items": {
"title": "Event",
"type": "object",
"properties": {
"type": {
"type": "string"
},
"handler": {
"type": "object"
},
"dependencies": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
}
},
"$ref": "#/definitions/TPNode"
}
Use the id
of the schema you need to reference
'$ref': 'tp_node'
See here: http://json-schema.org/latest/json-schema-core.html#anchor30
Yes, your schema will work. The "$ref": "#"
points back to the root of the schema document.
However, the "type": "object"
is useless:
{
'type': 'object',
'$ref': '#'
}
If $ref
is present, then all other keywords are ignored. It would be better to remove type
from the #/properties/children/items
schema.
Recursion example.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"person": {
"type": "object",
"properties": {
"name": { "type": "string" },
"children": {
"type": "array",
"items": { "$ref": "#/definitions/person" },
"default": []
}
}
}
},
"type": "object",
"properties": {
"person": { "$ref": "#/definitions/person" }
}
}