JSON Schema Tutorial: Validate JSON Data in JavaScript and Python
A JSON validator tells you whether text is valid JSON. A JSON Schema goes further: it describes what valid data looks like (which fields are required, their types, allowed values) so you can reject a bad API request or config file before it causes a bug. This tutorial builds one schema step by step and validates it in JavaScript and Python. All outputs below are real, from Ajv 8 and Python jsonschema 4.
The data we want to check
{ "id": 7, "name": "Ann", "email": "ann@example.com", "age": 34, "role": "admin", "tags": ["beta"] }The schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 },
"role": { "enum": ["admin", "editor", "viewer"] },
"tags": { "type": "array", "items": { "type": "string" }, "uniqueItems": true }
},
"additionalProperties": false
}Reading it line by line:
$schemasays which version of JSON Schema you use. 2020-12 is the current one; older schemas often say draft-07.type: one ofobject,array,string,number,integer,boolean,null.requiredlists keys that must exist. Keys inpropertiesare optional unless listed here.minimum/maximumfor numbers,minLength/maxLength/patternfor strings.enumallows only the listed values.itemsdescribes every array element;uniqueItemsrejects duplicates.additionalProperties: falserejects keys that aren’t listed – great for catching typos like"emial".
Validate in JavaScript (Ajv)
npm install ajv ajv-formatsimport Ajv from 'ajv/dist/2020.js' // the 2020-12 build
import addFormats from 'ajv-formats'
const ajv = new Ajv({ allErrors: true }) // report every error, not just the first
addFormats(ajv) // enables "email", "date-time", "uri"…
const validate = ajv.compile(schema) // compile once, reuse many times
if (!validate(data)) {
for (const e of validate.errors) console.log(e.instancePath || '(root)', e.message)
}With this invalid input – { "id": "7", "name": "", "email": "not-an-email", "age": -1, "role": "owner", "nickname": "A" } – Ajv reports:
(root) must NOT have additional properties
/id must be integer
/name must NOT have fewer than 1 characters
/email must match format "email"
/age must be >= 0
/role must be equal to one of the allowed values•
no schema with key or ref "https://json-schema.org/draft/2020-12/schema" – you imported the default ajv (draft-07) for a 2020-12 schema. Import ajv/dist/2020 instead.•
unknown format "email" ignored in schema – add ajv-formats.Validate in Python (jsonschema)
pip install jsonschemaimport json
from jsonschema import Draft202012Validator, FormatChecker
schema = json.load(open("schema.json"))
validator = Draft202012Validator(schema, format_checker=FormatChecker())
errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
for e in errors:
path = "/".join(str(p) for p in e.path) or "(root)"
print(f"{path}: {e.message}")(root): Additional properties are not allowed ('nickname' was unexpected)
age: -1 is less than the minimum of 0
email: 'not-an-email' is not a 'email'
id: '7' is not of type 'integer'
name: '' should be non-empty
role: 'owner' is not one of ['admin', 'editor', 'viewer']format_checker=FormatChecker(), Python’s jsonschema silently ignores format – an email of "nope" passes. The same is true in many other libraries: formats are “annotations” unless you turn checking on.For a quick yes/no, jsonschema.validate(data, schema) raises a ValidationError with the first problem, e.g. 'x' is not of type 'integer'.
More building blocks
{
"price": { "type": "number", "exclusiveMinimum": 0 },
"sku": { "type": "string", "pattern": "^[A-Z]{3}-\\d{4}$" },
"website": { "type": ["string", "null"], "format": "uri" },
"created": { "type": "string", "format": "date-time" },
"status": { "const": "active" },
"items": { "type": "array", "minItems": 1, "maxItems": 100 }
}Reuse definitions with $defs and $ref instead of copying the same object shape around:
{
"$defs": {
"address": {
"type": "object",
"required": ["city"],
"properties": { "city": { "type": "string" }, "zip": { "type": "string" } }
}
},
"type": "object",
"properties": {
"billing": { "$ref": "#/$defs/address" },
"shipping": { "$ref": "#/$defs/address" }
}
}Combine rules with anyOf (at least one matches), oneOf (exactly one) and allOf (all). Use oneOf sparingly – when two options overlap, valid data fails with confusing errors.
Tips from real projects
- Validate at the edges: incoming API requests, uploaded files, config at startup. Inside your code, trust your types.
- Use
integerfor IDs and counts,numberfor money only if you accept floating-point – many APIs send money as a string or in cents instead. - Start strict (
additionalProperties: false) for data you control; be lenient for third-party data that may gain new fields. - Generate types too. A schema checks data at runtime; TypeScript types help while writing code. You can draft types from sample data with the JSON to TypeScript generator.