A Beginner's Introduction to JSON Schema
A JSON validator tells you whether text is valid JSON. It can't tell you whether it's the right JSON: that the email field is there, the age is a number, and the role is one of the values your app understands. JSON Schema fills that gap. You describe what your data should look like, and a library checks real data against that description.
Why use JSON Schema?
Every program that receives JSON makes assumptions about it. When those assumptions are wrong, such as a missing field or a number sent as a string, the program fails somewhere deep in the code with an error like Cannot read properties of undefined, far from the real cause. Validating against a schema moves that failure to the front door, with a clear message about exactly which field is wrong.
Common uses:
- Checking request bodies in an API before your code touches them
- Validating config files when an app starts, with helpful messages for typos
- Editor support: VS Code uses schemas to autocomplete and check files like
package.jsonandtsconfig.jsonas you type - Documenting an API's data in a precise, machine-readable way (OpenAPI builds on it)
- Testing that an API still returns what its clients expect
Writing your first schema
Say your app stores users like this:
{
"id": 42,
"name": "Ada Lovelace",
"email": "ada@example.com",
"role": "admin",
"tags": ["math", "engines"]
}A schema is itself a JSON document. Here's one that describes a valid user, built up one rule at a time:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"properties": {
"id": { "type": "integer", "minimum": 1 },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"role": { "enum": ["admin", "editor", "viewer"] },
"tags": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
}
},
"required": ["id", "name", "email"],
"additionalProperties": false
}Read it from the top:
$schemasays which version of JSON Schema this uses. 2020-12 is the current version."type": "object": the data must be a JSON object.propertiesdescribes each key that may appear, with its own mini-schema. The ID must be a whole number of at least 1, the name a non-empty string, and the role one of three exact values.requiredlists keys that must be present.roleandtagsaren't listed, so they're optional, but must follow their rules when they do appear."additionalProperties": falserejects any key not listed inproperties, which catches typos like"emial".
The keywords you'll use most
| Keyword | Applies to | Meaning |
|---|---|---|
type | Anything | "string", "number", "integer", "boolean", "object", "array" or "null". Use a list, like ["string", "null"], to allow more than one |
enum | Anything | Must equal one of the listed values |
properties, required | Objects | Describe the keys, and which must be present |
additionalProperties | Objects | false to reject unlisted keys |
items | Arrays | Schema every element must match |
minItems, maxItems, uniqueItems | Arrays | Length limits and no duplicates |
minLength, maxLength, pattern | Strings | Length limits, and a regular expression to match |
format | Strings | Known formats like "email", "date", "date-time", "uri", "uuid" |
minimum, maximum | Numbers | Inclusive limits |
format isn't always enforced
By default the specification treats format as an annotation, not a rule, so many validators ignore it unless you turn format checking on. The examples below show how for each library.
What validation errors look like
Now try some data with several problems:
{
"id": "42",
"name": "Ada Lovelace",
"role": "owner",
"nickname": "Ada"
}This is perfectly valid JSON, and it would pass any JSON validator, including this site's tool. Against the schema, though, it has four problems: the ID is a string instead of a number, email is missing, owner isn't an allowed role, and nickname isn't a known key. A schema validator reports all of them.
Validating in JavaScript with Ajv
Ajv is the most widely used JSON Schema validator for JavaScript. Install it with the formats add-on:
npm install ajv ajv-formatsimport Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
const ajv = new Ajv2020({ allErrors: true }); // report every problem, not just the first
addFormats(ajv); // enable "format": "email" and friends
const validate = ajv.compile(schema); // compile once, reuse many times
if (!validate(data)) {
for (const err of validate.errors) {
console.log(err.instancePath || "(root)", err.message);
}
}For the data above, this prints:
(root) must have required property 'email'
(root) must NOT have additional properties
/id must be integer
/role must be equal to one of the allowed valuesinstancePath points at the field using a JSON Pointer, so /id is the id key at the top level, and /tags/0 would be the first tag. Ajv's default Ajv class uses the older draft-07 version of JSON Schema; import from ajv/dist/2020, as above, for 2020-12 schemas.
Validating in Python with jsonschema
In Python, the jsonschema package does the same job:
pip install jsonschemafrom jsonschema import Draft202012Validator, ValidationError, validate
# Quick check: raises ValidationError at the first problem
try:
validate(instance=data, schema=schema)
except ValidationError as e:
print(e.message) # 'email' is a required property
# Every problem at once
validator = Draft202012Validator(schema)
for error in validator.iter_errors(data):
print(list(error.path) or "(root)", error.message)(root) 'email' is a required property
(root) Additional properties are not allowed ('nickname' was unexpected)
['id'] '42' is not of type 'integer'
['role'] 'owner' is not one of ['admin', 'editor', 'viewer']To have format checked as well, pass format_checker=Draft202012Validator.FORMAT_CHECKER when you create the validator. Some formats, such as "uri", need extra packages; the jsonschema documentation lists which.
Where to go next
- Generate a first draft. Several tools can infer a schema from example JSON. Treat the result as a starting point: an example can't tell a tool which fields are optional or what values are allowed.
- Reuse pieces with
$defsand$ref, for example to describe an address once and use it for both billing and shipping. - Combine rules with
anyOf,oneOfandallOfwhen a value can take more than one shape. - Read the official guide. The JSON Schema getting-started guide walks through a larger example.