Recursive Schemas

In JSON Schema, recursive schemas allow you to define schemas that refer to themselves. This can be useful when working with hierarchical data structures or when modeling recursive relationships.

1{
2  
3  "name":"John Doe",
4  "links": [
5    {
6      "name": "Jane Doe",
7      "links": [
8        {
9          "name": "Alice Doe",
10          "links": []
11        },
12      ]
13    },
14    {
15      "name": "Jack Doe",
16      "links": []
17    }
18  ]
19}

To define a recursive schema, you can use the $ref keyword to refer to the schema itself. For example:

1{
2  "$defs": {
3    "TreeNode": {
4      "type":"array",
5      "items": {
6        "type":"object",
7        "properties": {
8          "name": { "type": "string" },
9          "children": { "$ref": "#/$defs/TreeNode" }
10        },
11        "required": ["name", "children"]
12      }
13    }
14  },
15  "$ref": "#/$defs/TreeNode",
16}

In the above example, the TreeNode schema refers to itself in the children property, creating a recursive structure.

Task

1{
2  "name": "John Doe",
3  "next":{
4    "value": "Jane Doe",
5    "next": {
6      "value": "Alice Doe",
7      "next": {}
8    }
9  }
10}

You are given an incomplete JSON Schema in the right side editor. Define the next schema using recursive schemas. here next is a linked list of values.

Hint:

  • inside $defs define a subschemas next that refers to itself and null as the base case.
  • You will define next property inside the $defs/next schema. the value of nextproperty can be either null or the next schema itself. you can use anyOf keyword to define multiple schemas.
Loading...
Output
Please click the button or use
Shift+Enter
to view the output