Open JSON File

Information, tips and instructions

JSON Schema

JSON schema concept is derived from the XML schema which is a document that is used to describe and validate XML documents. Similar to its ancestor JSON schema describes what data could be stored in complying JSON documents and how this data should be formatted. Depending on data that needs to be stored in JSON document the schema could vary.

JSON schema can precisely describe how JSON file should be structured, what data types certain fields should use, what values data types may have, and many more.

For example, let’s consider an example where we have a set of JSON documents defining rectangles. One of such documents is shown below.

{
 “width”: 10,
 “height”: 20
}

The schema describing these JSON documents would look as follow:

{
 “type”: “object”,
 “properties”: {
  “width”: {“type”: “number”},
  “height”: {“type”: “number”}
 }
}

This schema describes an element of type "object" which has two numeric properties: width and height. The schema above will only validate the data types of the width and height. It does not validate their presence in the object. Even empty {} object will be valid according to the schema above. To make the schema check that both of these properties are present we need to use “required” keyword.

{
 “type”: “object”,
 “properties”: {
  “width”: {“type”: “number”},
  “height”: {“type”: “number”}
 }
},
 “required”: [“width”, “height”]
}

The schema above will only validate objects which have both height and width present. Still, it would allow objects with additional properties like one below:

{
 “width”: 10,
 “height”: 20,
 “salary”: 300
}

To prevent objects like one below from validating and restrict properties only to width and height we need to use the "additionalProperties" modifier.

{
 “type”: “object”,
 “properties”: {
  “width”: {“type”: “number”},
  “height”: {“type”: “number”}
 },
 “required”: [“width”, “height”],
 “additionalProperties”: false
}

This schema modifier specifies that no properties other than defined in the schema will be accepted as valid.