JSON Schema Guide: Validate Your JSON Data
JSON Schema is a powerful tool for validating the structure and content of JSON data. It allows you to define rules for your data format, ensuring consistency and catching errors early in your development process.
What You'll Learn
- • What JSON Schema is and why it matters
- • Basic schema structure and keywords
- • Validating strings, numbers, arrays, and objects
- • Combining schemas with allOf, anyOf, oneOf
- • Real-world examples and best practices
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It's written in JSON itself, making it easy to read and write. Think of it as a contract that defines what your JSON data should look like.
Why Use JSON Schema?
- Validation: Automatically check if JSON data meets your requirements
- Documentation: Schemas serve as human-readable documentation
- Code Generation: Generate types for TypeScript, Java, and other languages
- API Design: Define request/response formats for REST APIs
- IDE Support: Get autocomplete and validation in your editor
Basic Schema Structure
Every JSON Schema starts with some basic metadata and type information:
Basic Schema Structure
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/user.schema.json",
"title": "User",
"description": "A user in our application",
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"email": { "type": "string", "format": "email" }
},
"required": ["id", "name", "email"]
}Type Keywords
JSON Schema supports all JSON types plus some additional validation keywords:
| Type | Description | Example |
|---|---|---|
| string | Text values | "hello" |
| number | Any number (int or float) | 42, 3.14 |
| integer | Whole numbers only | 42 |
| boolean | true or false | true |
| array | Ordered list | [1, 2, 3] |
| object | Key-value pairs | {"key": "value"} |
| null | Null value | null |
String Validation
{
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[a-zA-Z]+$",
"format": "email"
} Common format values: email, uri, date, date-time, uuid, ipv4, ipv6.
Number Validation
{
"type": "number",
"minimum": 0,
"maximum": 100,
"exclusiveMinimum": 0,
"multipleOf": 0.5
}Array Validation
{
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}Object Validation
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name"],
"additionalProperties": false
}Combining Schemas
allOf - Must Match All
{
"allOf": [
{ "$ref": "#/$defs/baseUser" },
{ "properties": { "role": { "type": "string" } } }
]
}anyOf - Must Match At Least One
{
"anyOf": [
{ "type": "string" },
{ "type": "number" }
]
}oneOf - Must Match Exactly One
{
"oneOf": [
{ "type": "integer" },
{ "type": "string", "pattern": "^[0-9]+$" }
]
}Real-World Example: User API
Complete User Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30,
"pattern": "^[a-z0-9_]+$"
},
"email": {
"type": "string",
"format": "email"
},
"profile": {
"type": "object",
"properties": {
"firstName": { "type": "string" },
"lastName": { "type": "string" },
"avatarUrl": { "type": "string", "format": "uri" }
},
"required": ["firstName", "lastName"]
},
"roles": {
"type": "array",
"items": {
"type": "string",
"enum": ["user", "admin", "moderator"]
},
"minItems": 1,
"uniqueItems": true
},
"createdAt": {
"type": "string",
"format": "date-time"
}
},
"required": ["id", "username", "email", "roles"]
}Using JSON Schema in JavaScript
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv();
addFormats(ajv);
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 };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}Best Practices
- Start simple: Begin with basic validation and add complexity as needed
- Use $ref: Reuse schema definitions to keep your schemas DRY
- Add descriptions: Document each property for better tooling support
- Set defaults: Define default values for optional properties
- Version your schemas: Use $id to version and track changes
Validate your JSON data now!
Try Our JSON Validator →