JSON Schema Guide: Draft 2020-12 Validation, Keywords, and Best Practices
Learn how to validate JSON data with JSON Schema: core keywords, type constraints, composition with allOf/anyOf/oneOf, Ajv integration, and TypeScript generation.
1. What is JSON Schema and Why Declarative Validation Matters
As applications grow into distributed microservices and public-facing APIs, validating incoming request payloads becomes vital for application stability and security. Hardcoding manual validation logic using dozens of `if (!body.email || typeof body.email !== 'string')` checks is error-prone, difficult to maintain, and impossible to share across programming languages.
JSON Schema provides a declarative, standardized vocabulary (governed by IETF specifications) to annotate and validate the structure, constraints, and data types of JSON documents. It acts as an executable contract between clients and servers.
2. Core Keywords: type, properties, required, and additionalProperties
Every JSON Schema starts by defining the root data type and structural constraints:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://webutil.tech/schemas/user.json",
"type": "object",
"required": ["id", "username", "email"],
"properties": {
"id": { "type": "integer", "minimum": 1 },
"username": { "type": "string", "minLength": 3, "maxLength": 20 },
"email": { "type": "string", "format": "email" },
"role": { "type": "string", "enum": ["admin", "editor", "viewer"] }
},
"additionalProperties": false
}
Setting `"additionalProperties": false` is a critical security best practice that prevents prototype pollution and unexpected payload injections.
3. Advanced Constraints: Arrays, items, and Numeric Ranges
Validating collections and numeric values requires specialized constraint keywords:
- Arrays: The `items` keyword specifies the schema for each array element. Use `minItems` and `maxItems` to control collection size, and `uniqueItems: true` to enforce set uniqueness.
- Numbers: Use `minimum`, `maximum`, `exclusiveMinimum`, and `multipleOf` (e.g. `"multipleOf": 0.01` for currency).
- Strings: Use `pattern` with standard regular expressions (e.g. `"pattern": "^[a-z0-9_-]+$"`), and `format` for semantic validation (date-time, uri, ipv4, ipv6).
4. Schema Composition: allOf, anyOf, oneOf, and Modular References ($ref)
JSON Schema supports composition and code reuse:
- `allOf`: The data must satisfy all subschemas (logical AND).
- `anyOf`: The data must satisfy at least one subschema (logical OR).
- `oneOf`: The data must satisfy exactly one subschema (mutually exclusive XOR).
- `$ref`: Allows referencing reusable schema definitions across files or within a `$defs` block, keeping complex schemas modular and DRY.
5. Validating JSON Schemas in Node.js with Ajv
Ajv (Another JSON Schema Validator) is the industry-standard JSON Schema validator for Node.js, compiling schemas into highly optimized JavaScript code:
```javascript import Ajv from 'ajv'; import addFormats from 'ajv-formats';
const ajv = new Ajv({ allErrors: true }); addFormats(ajv);
const schema = { type: 'object', properties: { email: { type: 'string', format: 'email' } }, required: ['email'], };
const validate = ajv.compile(schema); const valid = validate({ email: 'hello@webutil.tech' }); if (!valid) console.log(validate.errors); ```
6. Generating TypeScript Types Directly from JSON Schema
Instead of manually maintaining both TypeScript interfaces and JSON Schema files, automated tools like `json-schema-to-typescript` compile your schemas directly into strongly typed TypeScript declarations in your build pipeline, guaranteeing 100% type safety from database to frontend.
Recommended Articles & Guides
How to Format JSON Properly: A Complete Guide
Learn how to format JSON data correctly with best practices, common patterns, and troubleshooting tips for developers.
Common JSON Errors and How to Fix Them
A comprehensive guide to the most frequent JSON errors developers encounter and step-by-step solutions to fix them.
URL Encoding and Decoding: What Every Developer Should Know
Understand how URL encoding works, why it matters for web development, and how to properly encode and decode URLs.