Skip to content

JSON Schema tutorial: validate JSON with examples

Write a JSON Schema for real data, understand the keywords you'll use most, and validate JSON against it online, in JavaScript or in Python.

Guide6 min readUpdated

JSON Schema is a JSON document that describes what other JSON should look like: which fields exist, which are required, what type each one has and which values are allowed. Validating data against a schema catches bad API requests, broken config and integration mistakes before they cause bugs, and the schema doubles as documentation. Here's a user record and a schema for it:

{
  "id": 7,
  "name": "Ann",
  "email": "ann@example.com",
  "role": "admin",
  "tags": ["a", "b"]
}
The data
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "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
}
The schema

The keywords you'll use most

typeThe JSON type: string, number, integer, boolean, null, object or array.
propertiesA schema for each key of an object.
requiredKeys that must be present. Properties are optional unless listed here.
additionalPropertiesfalse rejects any key not listed in properties; catches typos and unexpected fields.
enumThe value must be one of a fixed list.
minLength / maxLengthLimits on string length.
minimum / maximumLimits on numbers.
patternA regular expression the string must match.
formatCommon string formats such as email, date, date-time, uri and uuid.
itemsA schema that every array item must match.
uniqueItemstrue rejects arrays with duplicate items.

Note that integer is stricter than number: 7 passes both, 7.5 only passes number.

What validation errors look like

Now validate some bad data against the same schema:

{ "id": "7", "name": "", "role": "owner", "nickname": "A" }

Every validator reports the same five problems, worded slightly differently:

  • email is required but missing.
  • id is the string "7", not an integer.
  • name is shorter than minLength.
  • role isn't one of the allowed values.
  • nickname isn't allowed, because additionalProperties is false.

Validate online

Paste the data and the schema into the JSON Schema Validator. Each violation is listed with its path, the rule that failed and the line in your data. It supports drafts 2020-12, 2019-09 and 07, and can infer a starting schema from your data so you don't have to write one from scratch. Everything runs in your browser.

Validate in JavaScript with Ajv

import Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats"; // needed for "format": "email" and friends

const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(schema);

if (!validate(data)) {
  console.log(validate.errors); // e.g. "/id must be integer"
}
npm install ajv ajv-formats. allErrors reports every problem instead of stopping at the first.

Validate in Python with jsonschema

from jsonschema import Draft202012Validator

validator = Draft202012Validator(schema)
for error in validator.iter_errors(data):
    print(list(error.path), error.message)  # ['id'] '7' is not of type 'integer'
pip install jsonschema

Tips

  • Check that the data is valid JSON first with the JSON Validator; schema validation only works on data that parses.
  • Use additionalProperties: false on API input to catch misspelt field names, which otherwise pass silently.
  • In TypeScript projects, you can also generate types from sample JSON with JSON to TypeScript to keep code and schema in step.

Frequently asked questions

Which JSON Schema version should I use?

Use draft 2020-12, the current version, for new schemas, and declare it with "$schema": "https://json-schema.org/draft/2020-12/schema". Draft-07 is still common in older tools and is very similar for everyday schemas.

Can I generate a schema from example JSON?

Yes. The JSON Schema Validator can infer a starting schema from your data. Review it afterwards: an example can't tell which fields are optional or which values are allowed.

Is a valid schema the same as valid JSON?

No. Valid JSON only means the syntax is correct. Schema validation checks that the data has the right shape: the expected fields, types and values.

Tools used in this guide

More guides