JSON Schema is the industry standard for defining and validating JSON data structures. Once you understand it, you can catch data errors before they reach your database or break your application.

A complete practical schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "id":    { "type": "string", "pattern": "^usr_[a-z0-9]+$" },
    "name":  { "type": "string", "minLength": 1, "maxLength": 100 },
    "age":   { "type": "integer", "minimum": 0, "maximum": 150 },
    "email": { "type": "string", "format": "email" },
    "role":  { "type": "string", "enum": ["admin", "user", "moderator"] },
    "score": { "type": "number", "minimum": 0, "maximum": 5 },
    "tags":  { "type": "array", "items": { "type": "string" }, "maxItems": 10 },
    "address": {
      "type": "object",
      "properties": {
        "city":    { "type": "string" },
        "country": { "type": "string", "minLength": 2, "maxLength": 2 }
      },
      "required": ["city", "country"]
    }
  },
  "required": ["id", "name", "email", "role"]
}

String constraints

{ "type": "string", "minLength": 1, "maxLength": 100 }
{ "type": "string", "pattern": "^[a-zA-Z0-9_]+$" }
{ "type": "string", "format": "email" }
{ "type": "string", "format": "date" }      // "2023-11-14"
{ "type": "string", "format": "date-time" } // ISO 8601
{ "type": "string", "format": "uri" }
{ "type": "string", "enum": ["red", "green", "blue"] }

Number constraints

{ "type": "integer" }
{ "type": "number", "minimum": 0, "maximum": 100 }
{ "type": "number", "exclusiveMinimum": 0 }  // > 0, not >= 0
{ "type": "number", "multipleOf": 5 }         // 0, 5, 10, 15...

Combining schemas

// allOf — must match ALL schemas
{ "allOf": [{ "type": "string" }, { "minLength": 1 }] }

// anyOf — must match AT LEAST ONE
{ "anyOf": [{ "type": "string" }, { "type": "number" }] }

// oneOf — must match EXACTLY ONE
{ "oneOf": [{ "type": "string" }, { "type": "null" }] }

// not — must NOT match
{ "not": { "type": "null" } }  // anything except null

Conditional validation

// If type is "business", require company name
{
  "if": { "properties": { "type": { "const": "business" } } },
  "then": { "required": ["companyName"] },
  "else": { "required": ["firstName", "lastName"] }
}

Validate in JavaScript with AJV

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true }); // collect all errors, not just first
addFormats(ajv);

const validate = ajv.compile(schema);
const valid = validate(data);

if (!valid) {
  validate.errors.forEach(err => {
    console.log(`${err.instancePath}: ${err.message}`);
  });
}

Try it free — JSON Schema Validator

Validate JSON against your schema instantly — see all errors with field paths.

Open tool →