JSON Schema: A Complete Guide for Developers
JSON Schema is the industry standard for defining the structure, types, and constraints of JSON data. If you build APIs, validate configuration files, or exchange data between services, JSON Schema gives you a formal way to describe what your data should look like — and validate it automatically. This guide explains what JSON Schema is, why you need it, and how to create one from scratch or generate one from existing data.
What is JSON Schema?
JSON Schema is itself a JSON document that describes the shape of other JSON documents. Think of it as a blueprint or contract: it specifies which fields exist, what types they have (string, number, boolean, array, object), which fields are required, and what constraints apply (minimum/maximum values, string patterns, array lengths).
Here's a simple example. Given this JSON data:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}A JSON Schema describing this data would be:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"email": { "type": "string" }
},
"required": ["name", "age", "email"],
"additionalProperties": false
}This schema says: the data must be an object with three properties — name (string), age (integer), and email (string) — all of which are required, and no other properties are allowed.
Why Use JSON Schema?
- API validation — validate request bodies and query parameters before your code processes them. Reject malformed data at the boundary.
- Documentation — a schema is both human-readable documentation and machine-enforceable validation. Tools like Swagger/OpenAPI use JSON Schema to document API contracts.
- Code generation — generate TypeScript types, form validators, or database models from a schema.
- Configuration validation — validate config files (e.g., VS Code settings, ESLint configs) to catch typos and invalid values.
- Testing — assert that API responses match the expected shape in integration tests.
JSON Schema Data Types
JSON Schema supports seven primitive types:
| Type | Description | Example |
|---|---|---|
| string | Text data | "hello" |
| number | Any numeric value (float/int) | 3.14 |
| integer | Whole numbers only | 42 |
| boolean | True or false | true |
| object | Key-value pairs | {"key": "val"} |
| array | Ordered list of values | [1, 2, 3] |
| null | Explicit absence of value | null |
Key Schema Keywords
properties and required
The properties keyword defines the fields in an object and their schemas. The required keyword lists which fields must be present. Fields not in the required array are optional.
additionalProperties
Controls whether an object can contain fields not listed in properties. Set to false to enforce strict validation — any extra field causes a validation error. Useful for APIs where unexpected fields should be rejected.
items (for arrays)
Defines the schema for array elements. All items in the array must match this schema:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" }
},
"required": ["id", "name"]
}
}String Validation Keywords
minLength/maxLength— string length boundspattern— regex pattern the string must matchformat— semantic format like "email", "uri", "date", "uuid"enum— value must be one of a predefined set
Number Validation Keywords
minimum/maximum— inclusive boundsexclusiveMinimum/exclusiveMaximum— exclusive boundsmultipleOf— value must be a multiple of this number
Nested Objects and Complex Structures
Real-world JSON is rarely flat. Here's a schema for a more complex structure — a user with an address object and a tags array:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 },
"active": { "type": "boolean" },
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"zip": { "type": "string", "pattern": "^[0-9]{5}$" }
},
"required": ["street", "city", "zip"]
},
"tags": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
}
},
"required": ["id", "name", "email"],
"additionalProperties": false
}Generating JSON Schema from Existing Data
Writing schemas by hand is fine for small structures, but for complex JSON payloads with dozens of fields and deeply nested objects, it's faster to generate a schema from a sample JSON document and then customize it.
Our JSON Schema Generator does exactly this. Paste a sample JSON payload and get a complete JSON Schema with correct types, nested object support, and array item inference. Options let you mark all fields as required, control additional properties, and add a schema title.
If your JSON input is minified or messy, use the JSON Formatter to prettify it first.
Validating JSON Against a Schema
Once you have a schema, you can validate JSON data against it using libraries in any language:
// JavaScript (using ajv)
import Ajv from "ajv";
const ajv = new Ajv();
const schema = { /* your schema */ };
const validate = ajv.compile(schema);
const data = { name: "John", age: 30 };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}
// Python (using jsonschema)
from jsonschema import validate, ValidationError
import json
schema = { ... }
data = { "name": "John", "age": 30 }
try:
validate(instance=data, schema=schema)
print("Valid!")
except ValidationError as e:
print(f"Invalid: {e.message}")JSON Schema in OpenAPI / Swagger
OpenAPI (formerly Swagger) uses JSON Schema to define request and response bodies. If you're building a REST API, your OpenAPI specification already contains JSON Schemas — understanding the vocabulary helps you write better API documentation and catch validation issues before they reach production.
Key Takeaways
- JSON Schema describes the structure, types, and constraints of JSON data. It's used for validation, documentation, and code generation.
- The core keywords are
type,properties,required, anditems. Learn these four and you can describe most JSON structures. - Use
additionalProperties: falseto enforce strict validation and catch unexpected fields. - Generate schemas from sample data when dealing with complex structures, then customize the generated schema with constraints.
- Every major programming language has a JSON Schema validation library. Validate at system boundaries (API endpoints, config loading, form submission).
Generate JSON Schema from Your Data
Paste a JSON sample and get a complete JSON Schema with type inference, required fields, and nested object support. All processed locally in your browser.
Try These Free Tools
Related Articles
JSON Formatting and Validation: A Developer's Quick Guide
A practical guide to JSON formatting, validation, and common mistakes. Learn JSON best practices and how to convert between JSON and CSV quickly.
5 Free Online Tools Every Developer Needs
Discover the essential free online tools that every developer should bookmark — from JSON formatting and regex testing to Base64 encoding and UUID generation.
The Complete Guide to JWT Tokens for Web Developers
Everything web developers need to know about JWT tokens — the three parts explained, authentication flows, access vs refresh tokens, security best practices, and common vulnerabilities.