Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON Schema for Tree structure?

I have a tree structure and i would like to create a JSON schema.

The class structure

class Node {

   String id;
   List<Node> children = new ArrayList<>();

}

The JSON Schema so far:

{
  "name": "node",
  "type": "object",
  "properties": {
     "id": {
        "type": "string",
        "description": "The node id",
        "required": true
     }
     "children": {
        "type": "array",
        "items": {
           //The items of array should be node ?               
        }
     }
  }
}

My problem is that I do not know how should i describe the content "items" of array in JSON?

Thanks in advance for answer.

like image 647
Damian Leszczyński - Vash Avatar asked Mar 06 '14 14:03

Damian Leszczyński - Vash


People also ask

Is JSON a tree structure?

JSON has three types of nodes, which are Value, Object and Array. We know that JSON nodes have a hierarchical tree structure.

How do I specify a schema in a JSON file?

If you want to use a custom schema of your own that's part of your project, just click on your schema in Solution Explorer and then drag it to that dropdown list. Alternatively, you can use the $schema keyword in a JSON file to associate it with a schema.

What is JSON Schema with example?

JSON Schema is an IETF standard providing a format for what JSON data is required for a given application and how to interact with it. Applying such standards for a JSON document lets you enforce consistency and data validity across similar JSON data.


1 Answers

Just use a JSON reference to point back to the schema itself:

{
  "type": "object",
  "required": [ "id" ],
  "properties": {
     "id": {
        "type": "string",
        "description": "The node id"
     },
     "children": {
        "type": "array",
        "items": { "$ref": "#" }
     }
  }
}

The # JSON reference means in essence "the document itself". This therefore allows you to define recursive schemas, as here.

Note: rewritten so that it conforms to draft v4.

like image 123
fge Avatar answered Sep 21 '22 16:09

fge