JSON Schemas
A JSON Schema allows you to annotate and validate your JSON documents. It allows you to restrict the type of data entered.
Consider the following JSON document:
One object in this example uses a different date format to the other objects.
Also, the object uses born
(indicating when the artist was born) while others use formed
(when the artist/group formed).
JSON has no rule to say that certain objects must use a certain data type, or even contain the same fields. They don't even need to contain the same number of fields. For example, we could add a favoritecolor
field to one without adding it to the others.
Furthermore, there's no rule that says data must be in a certain format. For example, the born
field could've been represented in any of the following ways:
That's right... "Oooops!!!". You could put anything in there.
This flexibility is one of the things that makes JSON so easy to use. But it can also cause issues like the above. Many applications that read JSON files will require data to be in a standard format. But even if it gets past the application, humans will sure have a hard time working out exactly what date "I like oranges!" is.
Therefore, when working with JSON files, you'll often want to specify constraints that restrict the type of data that can go into the file.
For example, you might want all dates to be entered in a certain format, say YYYY-MM-DD
. Or you might want to make sure users only put a number into an age
field.
Creating a Schema
You can apply rules to your JSON files by creating a schema. A JSON Schema allows you to specify what type of data can go into your JSON files.
You can use a schema to validate the JSON file to ensure it contains only the correct type of data.
For example, you can use the following line to restrict an instance to a string:
Here's an example of a basic JSON Schema (provided by json-schema.org):
You could use this schema to validate that a user enters their name and age properly.
As you can see, the JSON Schema is in fact, JSON itself. So it's not always easy to tell whether you're looking at a JSON Schema or just an ordinary JSON document.
However, it's usually considered good practice to place a schema declaration at the top of a schema. This declares that it is a JSON Schema. And it can help you recognize whether it's a JSON Schema or just a regular JSON document.
To declare a JSON Schema, use the $schema
keyword. For example:
This example declares a JSON Schema written against the current version of the specification.
You can also explicitly state which version of the specification you're using. The following example declares a JSON Schema written against JSON Schema, draft version 4:
To create a JSON Schema, check out JSONSchema.net. This is an online tool that automatically generates JSON Schema from any JSON that you input.