Reputation: 1527
I have a JSON Schema
{
'description': 'TPNode',
'type': 'object',
'id': 'tp_node',
'properties': {
'selector': {
'type': 'string',
'required': true
},
'attributes': {
'type': 'array',
'items': {
'name': 'string',
'value': 'string'
}
},
'children': {
'type': 'array',
'items': {
'type': 'object',
'$ref': '#'
}
},
'events': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'type': {
'type': 'string'
},
'handler': {
'type': 'object'
},
'dependencies': {
'type': 'array',
'items': {
'type': 'string'
}
}
}
}
}
}
}
What I'm trying to express in the children property is that it's an array of objects with the same exact schema. Is this the correct way to describe it?
Upvotes: 23
Views: 31015
Reputation: 101
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" }
}
}
Upvotes: 10
Reputation: 12891
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.
Upvotes: 27
Reputation: 25419
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"
}
Upvotes: 8
Reputation: 11076
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
Upvotes: 22