Understanding JSON Schema Validation
2026-03-24#json-schema#validation#javascript#api
What is JSON Schema?
JSON Schema is a powerful vocabulary that allows you to annotate and validate JSON documents. It provides a standardized way to describe the structure, data types, and constraints of your JSON data.
Why Use JSON Schema?
- Data Validation - Ensure your JSON data meets specific requirements before processing
- Documentation - Automatically generate documentation from schema definitions
- Code Generation - Generate type definitions and validation code
- API Contracts - Define clear contracts between services
Basic Schema Structure
A JSON Schema always starts with a root object that uses the $schema keyword:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object"
}
Defining Object Properties
{
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
Validating Arrays
Arrays can be validated with specific item schemas:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"productId": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 }
}
},
"minItems": 1,
"maxItems": 100
}
Using Enums
Restrict values to a predefined set:
{
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["pending", "processing", "completed", "failed"]
}
}
}
Pattern Matching
Use regular expressions to validate string formats:
{
"type": "object",
"properties": {
"phone": {
"type": "string",
"pattern": "^\\+?[1-9]\\d{1,14}$"
},
"zipCode": {
"type": "string",
"pattern": "^\\d{5}(-\\d{4})?$"
}
}
}
Nested Schemas
Create complex nested validation:
{
"type": "object",
"properties": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"country": { "type": "string", "minLength": 2 }
},
"required": ["city", "country"]
},
"contacts": {
"type": "array",
"items": { "$ref": "#/$defs/contact" }
}
},
"$defs": {
"contact": {
"type": "object",
"properties": {
"type": { "type": "string", "enum": ["email", "phone"] },
"value": { "type": "string" }
}
}
}
}
Validating with Code
Here's how to validate JSON against a schema using JavaScript:
import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer", minimum: 0 }
},
required: ["name"]
};
const validate = ajv.compile(schema);
const data = { name: "John", age: 30 };
if (validate(data)) {
console.log("Valid!");
} else {
console.log("Errors:", validate.errors);
}
Common Validation Keywords
| Keyword | Description |
|---|---|
type |
Specifies the data type |
required |
Array of required property names |
properties |
Defines object properties |
items |
Schema for array items |
enum |
Restricts to specific values |
minimum / maximum |
Numeric constraints |
minLength / maxLength |
String length constraints |
pattern |
Regular expression pattern |
format |
Pre-defined format validation |
Conclusion
JSON Schema is an essential tool for any developer working with JSON data. It provides a declarative, human-readable way to define the structure and constraints of your data, making your applications more robust and self-documenting.
Related articles
Working with Large JSON Files
Essential techniques for handling, parsing, and processing large JSON files efficiently without running into memory issues.
JSON Best Practices for Modern APIs
Design principles and patterns for building robust, developer-friendly APIs using JSON as the data exchange format.
Working with Large JSON Files - A Practical Guide
Techniques and tools for handling JSON files that exceed memory limits or browser constraints.
JSON vs XML - Choosing the Right Format for Your Use Case
A comprehensive comparison of JSON and XML to help you make informed format decisions.
JSON Tools Ecosystem - A Comprehensive Overview
Explore the best tools, libraries, and utilities for working with JSON across different platforms and use cases.
JSON Security Best Practices - Protecting Your Applications
Essential security measures for handling JSON data safely and preventing common vulnerabilities.