JSON Schema Guide
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the structure, data types, and constraints that a JSON document must conform to. JSON Schema is widely used for API documentation, input validation, code generation, and testing.
What is JSON Schema?
A JSON Schema is itself a JSON document that describes the expected structure of another JSON document. It specifies what keys are required, what data types each value must be, what format strings should follow, and what constraints numbers must satisfy. Think of it as a contract for your JSON data.
Basic JSON Schema Example
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "User",
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "integer",
"description": "Unique user identifier"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"active": {
"type": "boolean",
"default": true
}
}
}
Core JSON Schema Keywords
type
Specifies the data type. Values: string, number, integer, boolean, array, object, null.
required
An array of property names that must be present in the object. Missing required properties cause validation to fail.
properties
Defines the schema for each property of an object. Each key maps to a sub-schema that the property's value must satisfy.
additionalProperties
Controls whether properties not listed in properties are allowed. Set to false to reject unknown keys.
items
Defines the schema for items in an array. All items in the array must conform to this sub-schema.
enum
Restricts a value to a fixed set of allowed values. Example: "enum": ["admin", "user", "guest"]
String Validation Keywords
minLength/maxLength— minimum and maximum string lengthpattern— a regular expression the string must matchformat— semantic validation:email,uri,date,date-time,uuid
Number Validation Keywords
minimum/maximum— inclusive boundsexclusiveMinimum/exclusiveMaximum— exclusive boundsmultipleOf— value must be a multiple of this number
Array Validation Keywords
minItems/maxItems— minimum and maximum number of itemsuniqueItems— iftrue, all items must be uniquecontains— at least one item must match this sub-schema
Where JSON Schema Is Used
- API documentation — OpenAPI/Swagger uses JSON Schema to document request and response bodies
- Server-side validation — validate incoming API request bodies before processing
- Form validation — libraries like react-jsonschema-form generate forms from schemas
- Code generation — generate TypeScript types, Python dataclasses, or Java POJOs from schemas
- Configuration validation — VS Code uses JSON Schema to validate settings.json and other config files
- Testing — validate API responses in automated tests against expected schemas
Use JSONHack's free JSON validator to check syntax before applying schema validation.