What is JSON Schema?
JSON Schema is a declarative language that lets you describe the structure of your JSON data and validate it automatically. Think of it as a blueprint for your JSON. Just as a building blueprint specifies where walls, doors, and windows must go, a JSON Schema specifies which fields your data must contain, what types those fields should be, and what constraints they must satisfy.
JSON Schema is itself written in JSON, which makes it easy to read, write, and share. It follows a standard maintained by the JSON Schema organization, with the latest stable version being Draft 2020-12. Validators exist for virtually every programming language, so you can enforce your schema in JavaScript, Python, Java, Go, C#, Ruby, and many others.
Here is the simplest possible JSON Schema. It says "this value must be a string":
{
"type": "string"
}That single rule will accept "hello" and reject 42, true, ornull. From this tiny starting point, you can build schemas that validate complex API payloads, configuration files, database records, and form submissions with dozens of interconnected rules.
Throughout this tutorial, we will build progressively more sophisticated schemas. By the end, you will be comfortable writing production-ready schemas for real applications.
Why Use JSON Schema?
Before diving into syntax, let's understand why JSON Schema is worth learning. If you have ever spent hours debugging a crash caused by a missing field or an unexpected data type, JSON Schema solves that problem at the boundary, before bad data enters your system.
1. API Contract Enforcement
When a frontend sends a request to a backend, both sides need to agree on the shape of the data. JSON Schema acts as a machine-readable contract. If the request body doesn't match the schema, the server rejects it immediately with a clear error message. No more guessing what went wrong three layers deep in your business logic.
// Express.js middleware example
const Ajv = require("ajv");
const ajv = new Ajv();
const validate = ajv.compile(userSchema);
app.post("/api/users", (req, res) => {
const valid = validate(req.body);
if (!valid) {
return res.status(400).json({
errors: validate.errors
});
}
// Safe to proceed: req.body matches the schema
createUser(req.body);
});2. Documentation That Never Goes Stale
A JSON Schema doubles as documentation. Unlike a wiki page that someone forgets to update, the schema is the source of truth. Tools like Swagger/OpenAPI use JSON Schema to generate interactive API docs automatically. When you change the schema, the docs update themselves.
3. Form Validation
Libraries like react-jsonschema-form and ajv can generate entire HTML forms from a JSON Schema, complete with validation messages. You write the schema once, and both server and client enforce the same rules. This eliminates the common bug where the frontend allows data that the backend rejects.
4. Configuration File Validation
Applications that read JSON or YAML config files can validate them against a schema at startup. If the config file is malformed, the application fails fast with a descriptive error instead of crashing unpredictably at runtime. VS Code, ESLint, and many other tools use JSON Schema to power autocomplete and error checking in config files.
5. Code Generation
JSON Schema can drive code generation. Tools exist that turn a schema into TypeScript interfaces, Go structs, Python dataclasses, and more. This keeps your types in sync with your validation rules automatically.
// Generated TypeScript from JSON Schema
interface User {
id: number;
name: string;
email: string;
role: "admin" | "editor" | "viewer";
createdAt: string;
}Your First Schema
Let's start with a practical example. Suppose your application manages user profiles. A user object looks like this:
{
"id": 1,
"name": "Alice Johnson",
"email": "[email protected]",
"age": 30,
"isActive": true
}Here is the JSON Schema that validates this object:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User Profile",
"description": "Schema for a user profile object",
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "Unique identifier for the user"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "Full name of the user"
},
"email": {
"type": "string",
"format": "email",
"description": "Email address of the user"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150,
"description": "Age in years"
},
"isActive": {
"type": "boolean",
"description": "Whether the account is active"
}
},
"required": ["id", "name", "email"],
"additionalProperties": false
}Let's break down each piece of this schema:
$schema: Declares which version of JSON Schema you are using. This helps validators know which features are available.titleanddescription: Human-readable metadata. These don't affect validation but appear in generated documentation and error messages.type: The root data type. Here it's"object", meaning the top-level value must be a JSON object (curly braces).properties: Defines the expected keys and their validation rules. Each property has its own mini-schema.required: An array of property names that must be present. Missing any of these causes a validation failure.additionalProperties: When set tofalse, the object cannot contain any keys not listed inproperties. This is useful for catching typos like"emial"instead of"email".
This data would pass validation:
{
"id": 1,
"name": "Alice Johnson",
"email": "[email protected]",
"age": 30,
"isActive": true
}This data would fail validation (missing required email, and nameis empty):
{
"id": 2,
"name": "",
"age": -5
}The validator would report two errors: name must have at least 1 character (minLength: 1), email is required but missing, and age must be at least 0.
Data Types and Constraints
JSON Schema supports six primitive types plus the null type. Each type has its own set of validation keywords. Let's cover every type with its most useful constraints.
String
Strings are the most commonly constrained type. You can limit length, enforce patterns with regular expressions, and validate well-known formats.
{
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30,
"pattern": "^[a-zA-Z0-9_]+$",
"description": "Alphanumeric username, 3 to 30 characters"
},
"email": {
"type": "string",
"format": "email",
"description": "Must be a valid email address"
},
"birthDate": {
"type": "string",
"format": "date",
"description": "ISO 8601 date, e.g. 2026-02-10"
},
"website": {
"type": "string",
"format": "uri",
"description": "Must be a valid URL"
},
"bio": {
"type": "string",
"maxLength": 500,
"description": "Short biography, up to 500 characters"
},
"hexColor": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$",
"description": "Hex color code like #FF5733"
}
}
}The format keyword supports many built-in values: "email", "date","date-time", "uri", "uuid", "ipv4","ipv6", "hostname", and "regex". Note that some validators treatformat as an annotation only (not enforced) unless you enable format validation explicitly.
Number and Integer
Use "type": "number" for any numeric value (including decimals) and "type": "integer"for whole numbers only.
{
"type": "object",
"properties": {
"price": {
"type": "number",
"minimum": 0,
"exclusiveMaximum": 1000000,
"description": "Product price, must be non-negative and below 1 million"
},
"quantity": {
"type": "integer",
"minimum": 1,
"maximum": 9999,
"description": "Order quantity, at least 1"
},
"discount": {
"type": "number",
"minimum": 0,
"maximum": 100,
"multipleOf": 0.01,
"description": "Discount percentage with up to 2 decimal places"
},
"rating": {
"type": "number",
"minimum": 0,
"maximum": 5,
"multipleOf": 0.5,
"description": "Rating from 0 to 5 in 0.5 increments"
}
}
}The multipleOf keyword is especially useful. Setting it to 0.01 enforces two decimal places for currency values. Setting it to 0.5 allows only half-star ratings.
Boolean
Booleans are straightforward. They accept only true or false.
{
"type": "object",
"properties": {
"isVerified": {
"type": "boolean",
"description": "Whether the email has been verified"
},
"acceptsMarketing": {
"type": "boolean",
"default": false,
"description": "Opted in to marketing emails"
}
}
}The default keyword doesn't enforce anything during validation. It's a hint to consuming applications about what value to use when the field is absent.
Null
Sometimes a field must explicitly be null. You can also combine null with other types to make a field nullable.
{
"type": "object",
"properties": {
"deletedAt": {
"type": ["string", "null"],
"format": "date-time",
"description": "Timestamp when deleted, or null if not deleted"
},
"middleName": {
"type": ["string", "null"],
"description": "Middle name, or null if not provided"
}
}
}Enum
The enum keyword restricts a value to a fixed set of options. It works with any type.
{
"type": "object",
"properties": {
"role": {
"type": "string",
"enum": ["admin", "editor", "viewer", "guest"],
"description": "User role within the application"
},
"priority": {
"type": "integer",
"enum": [1, 2, 3, 4, 5],
"description": "Task priority level"
},
"status": {
"type": "string",
"enum": ["draft", "published", "archived"],
"default": "draft",
"description": "Content publication status"
},
"theme": {
"enum": ["light", "dark", "auto", null],
"description": "UI theme preference, or null for system default"
}
}
}Notice that the theme field omits "type" entirely and includes nulldirectly in the enum list. This is valid and sometimes cleaner than using a type array.
Defining Object Properties
Objects are the backbone of most JSON data. JSON Schema gives you fine-grained control over which properties an object may have, which are mandatory, and whether unknown properties are allowed. Let's explore this with a realistic example: creating a product in an e-commerce API.
properties and required
The properties keyword defines the known fields and their schemas. The requiredarray lists which of those fields must be present.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Create Product Request",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"slug": {
"type": "string",
"pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
"description": "URL-friendly identifier like 'wireless-headphones'"
},
"description": {
"type": "string",
"maxLength": 5000
},
"price": {
"type": "number",
"minimum": 0,
"multipleOf": 0.01
},
"compareAtPrice": {
"type": ["number", "null"],
"minimum": 0,
"multipleOf": 0.01,
"description": "Original price before discount, or null"
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP", "CAD", "AUD"],
"default": "USD"
},
"sku": {
"type": "string",
"pattern": "^[A-Z]{2,4}-[0-9]{4,8}$",
"description": "Stock keeping unit like 'WH-12345'"
},
"inventory": {
"type": "integer",
"minimum": 0
},
"isPublished": {
"type": "boolean",
"default": false
},
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1 },
"maxItems": 20,
"uniqueItems": true
},
"category": {
"type": "string",
"enum": ["electronics", "clothing", "home", "sports", "books", "other"]
},
"weight": {
"type": "object",
"properties": {
"value": { "type": "number", "minimum": 0 },
"unit": { "type": "string", "enum": ["kg", "lb", "g", "oz"] }
},
"required": ["value", "unit"]
},
"metadata": {
"type": "object",
"description": "Arbitrary key-value pairs for custom data"
}
},
"required": ["name", "price", "currency", "sku", "category"],
"additionalProperties": false
}additionalProperties
Setting "additionalProperties": false rejects any property not listed in properties. This is strict but safe for API request validation. You can also set it to a schema to allow extra properties that match a rule:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" }
},
"additionalProperties": {
"type": "string",
"maxLength": 100
}
}This allows any extra properties, but they must all be strings of 100 characters or fewer.
patternProperties
When you need to validate properties whose names follow a pattern, use patternProperties. This is common for localized content or dynamic keys.
{
"type": "object",
"properties": {
"id": { "type": "string" }
},
"patternProperties": {
"^name_[a-z]{2}$": {
"type": "string",
"minLength": 1,
"maxLength": 200,
"description": "Localized product name, e.g. name_en, name_fr, name_de"
},
"^description_[a-z]{2}$": {
"type": "string",
"maxLength": 5000,
"description": "Localized product description"
}
},
"additionalProperties": false
}This schema accepts name_en, name_fr, description_es, and so on, while rejecting keys like name_english or title_en.
minProperties and maxProperties
These keywords constrain the total number of properties in an object.
{
"type": "object",
"description": "User preferences, at least 1 and at most 50 settings",
"minProperties": 1,
"maxProperties": 50,
"additionalProperties": {
"type": ["string", "number", "boolean"]
}
}This is useful for freeform key-value stores where you want to prevent empty objects or excessively large payloads.
Validating Arrays
Arrays are the second most common structure in JSON data. JSON Schema lets you validate the items inside an array, constrain its length, enforce uniqueness, and even define tuple-like structures where each position has a different schema. Let's use a shopping cart as our running example.
items
The items keyword defines a schema that every element in the array must satisfy.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Shopping Cart",
"type": "object",
"properties": {
"cartId": {
"type": "string",
"format": "uuid"
},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"productId": {
"type": "string",
"format": "uuid"
},
"name": {
"type": "string",
"minLength": 1
},
"quantity": {
"type": "integer",
"minimum": 1,
"maximum": 100
},
"unitPrice": {
"type": "number",
"minimum": 0,
"multipleOf": 0.01
},
"variant": {
"type": "object",
"properties": {
"size": { "type": "string", "enum": ["XS", "S", "M", "L", "XL", "XXL"] },
"color": { "type": "string" }
}
}
},
"required": ["productId", "name", "quantity", "unitPrice"]
},
"minItems": 1,
"maxItems": 50,
"description": "Cart must contain at least one item and at most 50"
},
"couponCode": {
"type": ["string", "null"],
"pattern": "^[A-Z0-9]{5,15}$"
}
},
"required": ["cartId", "items"]
}minItems, maxItems, and uniqueItems
These keywords control the size and uniqueness of arrays.
{
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1 },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true,
"description": "Between 1 and 10 unique tags"
},
"scores": {
"type": "array",
"items": { "type": "number", "minimum": 0, "maximum": 100 },
"minItems": 3,
"maxItems": 3,
"description": "Exactly 3 scores between 0 and 100"
}
}
}Setting both minItems and maxItems to the same value enforces an exact length. The uniqueItems keyword rejects arrays with duplicate values.
contains
The contains keyword requires that at least one item in the array matches a given schema. You can combine it with minContains and maxContains for more control.
{
"type": "array",
"items": {
"type": "object",
"properties": {
"role": { "type": "string" },
"name": { "type": "string" }
},
"required": ["role", "name"]
},
"contains": {
"type": "object",
"properties": {
"role": { "const": "admin" }
},
"required": ["role"]
},
"minContains": 1,
"maxContains": 3,
"description": "Team must have between 1 and 3 admins"
}prefixItems (Tuple Validation)
Sometimes an array represents a fixed structure where each position has a different meaning. This is called a tuple. Use prefixItems to validate each position independently.
{
"type": "object",
"properties": {
"coordinates": {
"type": "array",
"prefixItems": [
{
"type": "number",
"minimum": -90,
"maximum": 90,
"description": "Latitude"
},
{
"type": "number",
"minimum": -180,
"maximum": 180,
"description": "Longitude"
},
{
"type": "number",
"minimum": 0,
"description": "Altitude in meters (optional)"
}
],
"minItems": 2,
"maxItems": 3,
"items": false,
"description": "Geographic coordinates as [lat, lng] or [lat, lng, alt]"
},
"colorRGBA": {
"type": "array",
"prefixItems": [
{ "type": "integer", "minimum": 0, "maximum": 255 },
{ "type": "integer", "minimum": 0, "maximum": 255 },
{ "type": "integer", "minimum": 0, "maximum": 255 },
{ "type": "number", "minimum": 0, "maximum": 1 }
],
"minItems": 4,
"maxItems": 4,
"items": false,
"description": "RGBA color as [red, green, blue, alpha]"
}
}
}Setting "items": false after prefixItems prevents additional items beyond the defined positions. Without it, extra items would be allowed.
Reusing Schemas with $ref
Real-world schemas often repeat the same structure in multiple places. An address appears in both billing and shipping. A money amount with currency appears on every line item and in every total. Copying and pasting the same schema fragment leads to maintenance headaches. This is where $ref and$defs come in.
The $defs keyword (previously called definitions in older drafts) is a container for reusable schema fragments. The $ref keyword points to one of those fragments by its JSON Pointer path.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Order",
"type": "object",
"$defs": {
"address": {
"type": "object",
"properties": {
"street": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"street2": {
"type": ["string", "null"],
"maxLength": 200,
"description": "Apartment, suite, or unit number"
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"state": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"postalCode": {
"type": "string",
"pattern": "^[A-Z0-9 -]{3,10}$"
},
"country": {
"type": "string",
"minLength": 2,
"maxLength": 2,
"description": "ISO 3166-1 alpha-2 country code"
}
},
"required": ["street", "city", "state", "postalCode", "country"],
"additionalProperties": false
},
"money": {
"type": "object",
"properties": {
"amount": {
"type": "number",
"minimum": 0,
"multipleOf": 0.01
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP", "CAD", "AUD"]
}
},
"required": ["amount", "currency"],
"additionalProperties": false
}
},
"properties": {
"orderId": {
"type": "string",
"format": "uuid"
},
"billingAddress": {
"$ref": "#/$defs/address"
},
"shippingAddress": {
"$ref": "#/$defs/address"
},
"subtotal": {
"$ref": "#/$defs/money"
},
"tax": {
"$ref": "#/$defs/money"
},
"shipping": {
"$ref": "#/$defs/money"
},
"total": {
"$ref": "#/$defs/money"
},
"lineItems": {
"type": "array",
"items": {
"type": "object",
"properties": {
"productId": { "type": "string" },
"name": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 },
"unitPrice": { "$ref": "#/$defs/money" },
"lineTotal": { "$ref": "#/$defs/money" }
},
"required": ["productId", "name", "quantity", "unitPrice", "lineTotal"]
},
"minItems": 1
}
},
"required": [
"orderId",
"billingAddress",
"shippingAddress",
"subtotal",
"tax",
"total",
"lineItems"
]
}In this schema, the address definition is referenced twice (billing and shipping), and themoney definition is referenced six times (subtotal, tax, shipping cost, total, and twice per line item). If you ever need to add a new field to addresses, you change it in one place and both billing and shipping are updated.
You can also reference schemas across files using a URL or relative path in the $ref value:
{
"billingAddress": {
"$ref": "./schemas/address.json"
},
"shippingAddress": {
"$ref": "./schemas/address.json"
}
}This pattern is essential for large projects where schemas are split into separate files and managed independently.
Conditional Validation
Some of the most powerful features in JSON Schema are its composition keywords: if/then/else,oneOf, anyOf, and allOf. These let you express rules like "if the payment method is credit card, then the card number is required." Let's explore each one with a payment form example.
if / then / else
This is the most intuitive conditional. The if schema is tested against the data. If it passes, the then schema is also enforced. If it fails, the else schema is enforced instead.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Payment Form",
"type": "object",
"properties": {
"paymentMethod": {
"type": "string",
"enum": ["credit_card", "bank_transfer", "paypal"]
},
"amount": {
"type": "number",
"minimum": 0.01,
"multipleOf": 0.01
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP"]
}
},
"required": ["paymentMethod", "amount", "currency"],
"allOf": [
{
"if": {
"properties": {
"paymentMethod": { "const": "credit_card" }
}
},
"then": {
"properties": {
"cardNumber": {
"type": "string",
"pattern": "^[0-9]{13,19}$",
"description": "Card number, 13 to 19 digits"
},
"cardHolder": {
"type": "string",
"minLength": 1
},
"expiryMonth": {
"type": "integer",
"minimum": 1,
"maximum": 12
},
"expiryYear": {
"type": "integer",
"minimum": 2026,
"maximum": 2040
},
"cvv": {
"type": "string",
"pattern": "^[0-9]{3,4}$"
}
},
"required": ["cardNumber", "cardHolder", "expiryMonth", "expiryYear", "cvv"]
}
},
{
"if": {
"properties": {
"paymentMethod": { "const": "bank_transfer" }
}
},
"then": {
"properties": {
"bankName": {
"type": "string",
"minLength": 1
},
"accountNumber": {
"type": "string",
"pattern": "^[0-9]{8,17}$"
},
"routingNumber": {
"type": "string",
"pattern": "^[0-9]{9}$",
"description": "9-digit ABA routing number"
}
},
"required": ["bankName", "accountNumber", "routingNumber"]
}
},
{
"if": {
"properties": {
"paymentMethod": { "const": "paypal" }
}
},
"then": {
"properties": {
"paypalEmail": {
"type": "string",
"format": "email"
}
},
"required": ["paypalEmail"]
}
}
]
}Notice how each payment method requires completely different fields. A credit card needs card details, a bank transfer needs routing information, and PayPal only needs an email. The allOf array ensures all three conditional rules are evaluated.
oneOf
The oneOf keyword requires that the data matches exactly one of the listed schemas. This is useful for discriminated unions.
{
"type": "object",
"properties": {
"notification": {
"oneOf": [
{
"type": "object",
"properties": {
"type": { "const": "email" },
"to": { "type": "string", "format": "email" },
"subject": { "type": "string" },
"body": { "type": "string" }
},
"required": ["type", "to", "subject", "body"],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": { "const": "sms" },
"phoneNumber": { "type": "string", "pattern": "^\\+[0-9]{10,15}$" },
"message": { "type": "string", "maxLength": 160 }
},
"required": ["type", "phoneNumber", "message"],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": { "const": "push" },
"deviceToken": { "type": "string" },
"title": { "type": "string" },
"body": { "type": "string" }
},
"required": ["type", "deviceToken", "title", "body"],
"additionalProperties": false
}
]
}
}
}anyOf
The anyOf keyword requires that the data matches at least one of the listed schemas. It is more permissive than oneOf.
{
"type": "object",
"properties": {
"contact": {
"type": "object",
"anyOf": [
{
"properties": { "email": { "type": "string", "format": "email" } },
"required": ["email"]
},
{
"properties": { "phone": { "type": "string", "pattern": "^\\+[0-9]{10,15}$" } },
"required": ["phone"]
}
],
"description": "Must provide at least an email or a phone number (or both)"
}
}
}allOf
The allOf keyword requires that the data matches every listed schema. This is commonly used to combine a base schema with additional constraints.
{
"$defs": {
"baseEvent": {
"type": "object",
"properties": {
"eventId": { "type": "string", "format": "uuid" },
"timestamp": { "type": "string", "format": "date-time" },
"source": { "type": "string" }
},
"required": ["eventId", "timestamp", "source"]
}
},
"allOf": [
{ "$ref": "#/$defs/baseEvent" },
{
"properties": {
"eventType": { "const": "user.signup" },
"data": {
"type": "object",
"properties": {
"userId": { "type": "string" },
"email": { "type": "string", "format": "email" },
"plan": { "type": "string", "enum": ["free", "pro", "enterprise"] }
},
"required": ["userId", "email", "plan"]
}
},
"required": ["eventType", "data"]
}
]
}Here, allOf merges the base event fields (eventId, timestamp, source) with the specific signup event fields (eventType, data). The resulting schema requires all of them.
Real-World Examples
Let's put everything together with three complete, production-ready schemas you can copy and adapt for your own projects.
1. REST API Response Envelope
Most APIs wrap their responses in a standard envelope that includes status information, the actual data, pagination details, and an error array. Here is a schema for that envelope:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "API Response Envelope",
"description": "Standard wrapper for all API responses",
"type": "object",
"$defs": {
"paginationMeta": {
"type": "object",
"properties": {
"currentPage": {
"type": "integer",
"minimum": 1,
"description": "Current page number, starting at 1"
},
"perPage": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"description": "Number of items per page"
},
"totalItems": {
"type": "integer",
"minimum": 0,
"description": "Total number of items across all pages"
},
"totalPages": {
"type": "integer",
"minimum": 0,
"description": "Total number of pages"
},
"hasNextPage": {
"type": "boolean"
},
"hasPreviousPage": {
"type": "boolean"
}
},
"required": [
"currentPage",
"perPage",
"totalItems",
"totalPages",
"hasNextPage",
"hasPreviousPage"
],
"additionalProperties": false
},
"apiError": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Machine-readable error code like VALIDATION_ERROR"
},
"message": {
"type": "string",
"description": "Human-readable error message"
},
"field": {
"type": ["string", "null"],
"description": "The field that caused the error, if applicable"
},
"details": {
"type": ["object", "null"],
"description": "Additional error context"
}
},
"required": ["code", "message"],
"additionalProperties": false
}
},
"properties": {
"status": {
"type": "string",
"enum": ["success", "error"],
"description": "Overall response status"
},
"data": {
"description": "Response payload. Null when status is error."
},
"pagination": {
"oneOf": [
{ "$ref": "#/$defs/paginationMeta" },
{ "type": "null" }
],
"description": "Pagination metadata for list endpoints, null for single-resource endpoints"
},
"errors": {
"type": "array",
"items": { "$ref": "#/$defs/apiError" },
"default": [],
"description": "Array of errors. Empty when status is success."
},
"requestId": {
"type": "string",
"format": "uuid",
"description": "Unique request identifier for debugging and tracing"
},
"timestamp": {
"type": "string",
"format": "date-time",
"description": "Server timestamp when the response was generated"
}
},
"required": ["status", "data", "errors", "requestId", "timestamp"],
"additionalProperties": false,
"allOf": [
{
"if": {
"properties": { "status": { "const": "success" } }
},
"then": {
"properties": {
"errors": {
"type": "array",
"maxItems": 0
}
}
}
},
{
"if": {
"properties": { "status": { "const": "error" } }
},
"then": {
"properties": {
"data": { "type": "null" },
"errors": {
"type": "array",
"minItems": 1
}
}
}
}
]
}Notice how the conditional validation ensures consistency: a success response must have zero errors, and an error response must have null data with at least one error object. The pagination field is optional and only relevant for list endpoints.
2. Application Configuration File
This schema validates a JSON configuration file for a typical web application. It covers database settings, server settings, logging, and feature flags.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Application Configuration",
"description": "Configuration file for a web application",
"type": "object",
"properties": {
"database": {
"type": "object",
"properties": {
"host": {
"type": "string",
"format": "hostname",
"default": "localhost"
},
"port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"default": 5432
},
"name": {
"type": "string",
"minLength": 1,
"description": "Database name"
},
"username": {
"type": "string",
"minLength": 1
},
"password": {
"type": "string",
"minLength": 8,
"description": "Minimum 8 characters"
},
"ssl": {
"type": "boolean",
"default": true
},
"pool": {
"type": "object",
"properties": {
"min": {
"type": "integer",
"minimum": 0,
"default": 2
},
"max": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 10
},
"idleTimeoutMs": {
"type": "integer",
"minimum": 1000,
"default": 30000,
"description": "Close idle connections after this many milliseconds"
}
},
"additionalProperties": false
}
},
"required": ["host", "port", "name", "username", "password"],
"additionalProperties": false
},
"server": {
"type": "object",
"properties": {
"host": {
"type": "string",
"default": "0.0.0.0"
},
"port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"default": 3000
},
"cors": {
"type": "object",
"properties": {
"enabled": { "type": "boolean", "default": true },
"origins": {
"type": "array",
"items": { "type": "string", "format": "uri" },
"minItems": 1,
"description": "Allowed origins for CORS"
},
"methods": {
"type": "array",
"items": {
"type": "string",
"enum": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
},
"default": ["GET", "POST", "PUT", "DELETE"]
}
},
"additionalProperties": false
},
"rateLimiting": {
"type": "object",
"properties": {
"enabled": { "type": "boolean", "default": true },
"windowMs": {
"type": "integer",
"minimum": 1000,
"default": 900000,
"description": "Time window in milliseconds (default: 15 minutes)"
},
"maxRequests": {
"type": "integer",
"minimum": 1,
"default": 100,
"description": "Max requests per window per IP"
}
},
"additionalProperties": false
}
},
"required": ["port"],
"additionalProperties": false
},
"logging": {
"type": "object",
"properties": {
"level": {
"type": "string",
"enum": ["trace", "debug", "info", "warn", "error", "fatal"],
"default": "info"
},
"format": {
"type": "string",
"enum": ["json", "text", "pretty"],
"default": "json",
"description": "Log output format"
},
"outputs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["console", "file", "http"]
},
"path": {
"type": "string",
"description": "File path, only used when type is file"
},
"url": {
"type": "string",
"format": "uri",
"description": "Endpoint URL, only used when type is http"
}
},
"required": ["type"]
},
"minItems": 1,
"description": "At least one log output must be configured"
},
"redactFields": {
"type": "array",
"items": { "type": "string" },
"default": ["password", "token", "secret", "authorization"],
"description": "Field names to redact from log output"
}
},
"required": ["level", "outputs"],
"additionalProperties": false
},
"features": {
"type": "object",
"description": "Feature flags for gradual rollout",
"patternProperties": {
"^[a-z][a-zA-Z0-9]*$": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"rolloutPercentage": {
"type": "integer",
"minimum": 0,
"maximum": 100,
"default": 100,
"description": "Percentage of users who see this feature"
},
"allowedRoles": {
"type": "array",
"items": { "type": "string" },
"description": "Restrict feature to specific user roles"
}
},
"required": ["enabled"],
"additionalProperties": false
}
},
"additionalProperties": false
}
},
"required": ["database", "server", "logging"],
"additionalProperties": false
}This schema demonstrates several advanced techniques working together: nested objects with defaults,patternProperties for dynamic feature flag names, format validation for hostnames and URIs, and sensible constraints on port numbers and pool sizes. A developer who writes an invalid config will get a clear validation error at startup instead of a cryptic runtime failure.
3. User Registration Form Validation
This schema validates a user registration payload. It covers common registration fields along with password strength requirements, terms acceptance, and conditional fields based on account type.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User Registration",
"description": "Schema for user registration form data",
"type": "object",
"properties": {
"accountType": {
"type": "string",
"enum": ["personal", "business"],
"description": "Type of account being created"
},
"firstName": {
"type": "string",
"minLength": 1,
"maxLength": 50,
"pattern": "^[a-zA-Z\\s'-]+$",
"description": "Legal first name"
},
"lastName": {
"type": "string",
"minLength": 1,
"maxLength": 50,
"pattern": "^[a-zA-Z\\s'-]+$",
"description": "Legal last name"
},
"email": {
"type": "string",
"format": "email",
"maxLength": 254,
"description": "Primary email address"
},
"password": {
"type": "string",
"minLength": 10,
"maxLength": 128,
"pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).+$",
"description": "At least 10 characters with uppercase, lowercase, number, and special character"
},
"confirmPassword": {
"type": "string",
"description": "Must match the password field (enforce in application logic)"
},
"dateOfBirth": {
"type": "string",
"format": "date",
"description": "Date of birth in YYYY-MM-DD format"
},
"phone": {
"type": "string",
"pattern": "^\\+[1-9][0-9]{7,14}$",
"description": "Phone in E.164 format, e.g. +14155552671"
},
"address": {
"type": "object",
"properties": {
"street": { "type": "string", "minLength": 1, "maxLength": 200 },
"city": { "type": "string", "minLength": 1, "maxLength": 100 },
"state": { "type": "string", "minLength": 1, "maxLength": 100 },
"postalCode": { "type": "string", "pattern": "^[A-Z0-9 -]{3,10}$" },
"country": {
"type": "string",
"minLength": 2,
"maxLength": 2,
"description": "ISO 3166-1 alpha-2 country code"
}
},
"required": ["street", "city", "postalCode", "country"],
"additionalProperties": false
},
"preferences": {
"type": "object",
"properties": {
"language": {
"type": "string",
"pattern": "^[a-z]{2}(-[A-Z]{2})?$",
"default": "en",
"description": "BCP 47 language tag, e.g. en, en-US, fr-FR"
},
"timezone": {
"type": "string",
"description": "IANA timezone like America/New_York"
},
"marketingEmails": {
"type": "boolean",
"default": false
},
"twoFactorAuth": {
"type": "boolean",
"default": false
}
},
"additionalProperties": false
},
"termsAccepted": {
"type": "boolean",
"const": true,
"description": "Must be true to register"
},
"privacyPolicyAccepted": {
"type": "boolean",
"const": true,
"description": "Must be true to register"
},
"referralCode": {
"type": ["string", "null"],
"pattern": "^[A-Z0-9]{6,10}$",
"description": "Optional referral code"
}
},
"required": [
"accountType",
"firstName",
"lastName",
"email",
"password",
"confirmPassword",
"termsAccepted",
"privacyPolicyAccepted"
],
"additionalProperties": false,
"if": {
"properties": {
"accountType": { "const": "business" }
}
},
"then": {
"properties": {
"companyName": {
"type": "string",
"minLength": 1,
"maxLength": 200,
"description": "Legal business name"
},
"taxId": {
"type": "string",
"pattern": "^[A-Z0-9-]{5,20}$",
"description": "Tax identification number"
},
"companySize": {
"type": "string",
"enum": ["1-10", "11-50", "51-200", "201-1000", "1000+"]
},
"industry": {
"type": "string",
"enum": [
"technology",
"finance",
"healthcare",
"education",
"retail",
"manufacturing",
"other"
]
}
},
"required": ["companyName", "taxId"]
}
}This registration schema showcases several techniques that are valuable in production:
- Password strength via pattern: The regex enforces uppercase, lowercase, digit, and special character in any order using lookahead assertions.
const: truefor terms acceptance: The user must explicitly agree. Sendingfalsefails validation.- Conditional business fields: When
accountTypeis"business", the schema requirescompanyNameandtaxId. Personal accounts do not need these fields at all. - E.164 phone format: The pattern ensures international phone numbers are stored consistently.
Validating with Tools
Writing a schema is only half the job. You also need to validate actual data against it. Fortunately, the ecosystem around JSON Schema is rich and mature.
Online Validation with JSONEditor.net
If you want to validate JSON data quickly without setting up any local tooling, head over to the JSONEditor.net editor. Paste your JSON data into the editor, and it will highlight syntax errors instantly. The editor supports formatting, minifying, and tree-view exploration, which makes it easy to inspect complex payloads before running them against a schema.
For developers who need to convert between formats, the tools page offers converters for JSON to CSV, JSON to XML, JSON to YAML, and more. One especially useful tool is the JSON to TypeScript converter, which generates TypeScript interfaces from your JSON data. This pairs well with JSON Schema because you can validate incoming data with the schema at runtime, then use the generated TypeScript types for compile-time safety.
If you are working with tabular data that started as JSON, the JSON to CSV converter can flatten nested structures into spreadsheet-friendly rows and columns.
Programmatic Validation
For integrating JSON Schema validation into your application code, here are the most popular libraries by language:
JavaScript / TypeScript (Ajv)
const Ajv = require("ajv");
const addFormats = require("ajv-formats");
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const schema = {
type: "object",
properties: {
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 18 }
},
required: ["email", "age"]
};
const validate = ajv.compile(schema);
const data = { email: "[email protected]", age: 25 };
const valid = validate(data);
if (!valid) {
console.log("Validation errors:", validate.errors);
} else {
console.log("Data is valid!");
}Python (jsonschema)
import json
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 18}
},
"required": ["email", "age"]
}
data = {"email": "[email protected]", "age": 25}
try:
validate(instance=data, schema=schema)
print("Data is valid!")
except ValidationError as e:
print(f"Validation error: {e.message}")Go (gojsonschema)
package main
import (
"fmt"
"github.com/xeipuuv/gojsonschema"
)
func main() {
schemaLoader := gojsonschema.NewStringLoader(`{
"type": "object",
"properties": {
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 18}
},
"required": ["email", "age"]
}`)
documentLoader := gojsonschema.NewStringLoader(`{
"email": "[email protected]",
"age": 25
}`)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
panic(err)
}
if result.Valid() {
fmt.Println("Data is valid!")
} else {
for _, desc := range result.Errors() {
fmt.Printf("Validation error: %s\n", desc)
}
}
}CI/CD Integration
You can also validate JSON files as part of your continuous integration pipeline. This is particularly useful for configuration files, API contract tests, and data migration scripts.
# GitHub Actions example
name: Validate Config
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install ajv ajv-formats ajv-cli
- run: npx ajv validate -s schemas/config.schema.json -d config.jsonThis approach catches invalid configuration before it ever reaches production. If someone pushes a config change that violates the schema, the pipeline fails immediately with a descriptive error.
Conclusion
JSON Schema is one of those tools that pays for itself almost immediately. The time you invest in writing a schema is repaid many times over in bugs prevented, documentation generated, and confidence gained. Here is a quick recap of what we covered:
- Basics: The
type,properties, andrequiredkeywords form the foundation of every schema. - Data types: Strings, numbers, integers, booleans, null, and enums each have their own set of constraints like
minLength,pattern,minimum,multipleOf, andformat. - Objects: Use
additionalProperties,patternProperties, andminProperties/maxPropertiesfor precise control over object shape. - Arrays: Validate items, enforce length with
minItems/maxItems, ensure uniqueness, and define tuples withprefixItems. - Reuse: DRY up your schemas with
$refand$defsto avoid duplication and simplify maintenance. - Conditionals: Handle polymorphic data with
if/then/else,oneOf,anyOf, andallOf. - Real-world patterns: API response envelopes, configuration files, and registration forms demonstrate how all these features work together in production.
To get started right now, open the JSONEditor.net editor and paste one of the example schemas from this tutorial. Experiment by changing fields, adding new constraints, and testing with sample data. The interactive feedback loop is the fastest way to build intuition for JSON Schema.
For converting your validated JSON into other formats, explore the full suite of conversion tools available at JSONEditor.net. Whether you need to go from JSON to CSV, JSON to TypeScript, or JSON to YAML, the tools handle the transformation while preserving your data's integrity.
Ready to validate your data? Open JSONEditor.net and start building schemas today.