JSON Schemas

JSON is a very versatile means of creating and storing data in human-readable format. But this has some vocabulary which allows its users to validate and annotate JSON documents. In this tutorial, you will learn about writing JSON Schemas.

What are the Schemas in JSON?

For JSON based formats some specifications define the JSON structure. It is called Schemas of JSON. It was written and drafted under the IETF (Internet Engineering Task Force). So let us see how it helps us.

Schemas help in describing the existing data format given by the user. Moreover, it provides a machine-understandable as well as human-readable data format, which helps in setup automated test.

In any JSON documentation, where there is validation, it is termed an instance; and where there is any description within the documentation, it is termed as schema. The simplest form of Schema in JSON is a blank document because it allows everything to fit into it but at the same time describes nothing, which looks something like this:

{}

or

{

}

Moreover, constraints can be applied to any instance just by declaring a validation keyword such as: "type". For example:

Example:
{ "type" : "string" }
Example:
{
  "$schema": "http://w3schools.in/json-06/schema#",
  "title": "Professor",
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "subject_teach": {
      "description": "Howmany_subjects",
      "type": "integer",
      "minimum": 1
    }
  },
  "required": [
    "first_name",
    "last_name"
  ]
}

Where the keyword $schema defined that this schema is scripted and drafted under v4 specification.  "title": "Professor" gives the title for this schema. "description": "Howmany_subjects" provides a brief description of what your JSON schema will be having. The keyword "type" needs to be a JSON object which defined the type of constraints your JSON data will hold. "minimum" and "maximum" are two constraints set for providing validation to the minimum and maximum value in JSON. The keyword "required" tells that what fixed data is needed as required properties. These are the basic keywords used for defining the JSON schema.

More Common Keywords

  • maxLength: is the string instances length which is the maximum number of characters in that string.
  • minLength: is the string instances length which defined the minimum number of characters in that string.
  • pattern: is an instance of string that is considered valid when your regular expression in JSON matches with the instance effectively.