Understanding JSON Schema
JSON Schema is a JSON document that describes the structure of another JSON document. It defines what fields are required, what data types are allowed, and what constraints must be met.
Key Benefits:
- Validate API requests and responses
- Ensure configuration file integrity
- Document data structure expectations
- Auto-generate forms and UI from schemas
- Enable interoperability between systems
Basic Schema Structure
A simple JSON Schema requires a type definition and optional properties:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" }
},
"required": ["name"]
}This schema requires an object with name and age properties, where name must be a string and is required, while age is a number and is optional.
Common Schema Keywords
- type: Specifies the data type (string, number, integer, boolean, object, array, null)
- properties: Defines the properties of an object and their schemas
- required: Lists properties that must be present
- items: Defines the schema for array elements
- additionalProperties: Controls whether additional properties are allowed
String Validation
Length constraints
Control string length with minLength and maxLength.
{
"type": "string",
"minLength": 1,
"maxLength": 100
}Pattern matching
Use regex patterns to match specific string formats.
{
"type": "string",
"pattern": "^[a-zA-Z0-9]+$"
}Format validation
Validate common formats like email, URI, and dates.
{
"type": "string",
"format": "email"
}Supported formats: email, uri, date, time, datetime, uuid, and more.
Number Validation
Range constraints
Use minimum and maximum to set numeric ranges.
{
"type": "number",
"minimum": 0,
"maximum": 100
}Exclusive ranges
Use exclusiveMinimum and exclusiveMaximum for exclusive bounds.
{
"type": "number",
"exclusiveMinimum": 0,
"exclusiveMaximum": 100
}Multiple of
Use multipleOf to require numbers to be divisible by a specific value.
{
"type": "number",
"multipleOf": 5
}Object Validation
Property names
Constrain property names using pattern matching.
{
"type": "object",
"propertyNames": {
"pattern": "^[a-z_]+$"
}
}Additional properties
Control whether extra properties are allowed.
{
"type": "object",
"additionalProperties": false
}Dependencies
Require certain properties when other properties are present.
{
"type": "object",
"dependencies": {
"creditCard": ["billingAddress"]
}
}Array Validation
Item validation
Define the schema for array elements.
{
"type": "array",
"items": {
"type": "string"
}
}Tuple validation
Validate arrays with fixed-length and specific types at each position.
{
"type": "array",
"items": [
{ "type": "string" },
{ "type": "number" }
]
}Length constraints
Control array length and uniqueness.
{
"type": "array",
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}Conditional Validation
if/then/else
Apply different validation rules based on conditions.
{
"if": {
"properties": { "country": { "const": "US" } }
},
"then": {
"required": ["zipCode"]
},
"else": {
"required": ["postalCode"]
}
}anyOf, oneOf, allOf
Combine schemas using logical operators.
{
"anyOf": [
{ "type": "string" },
{ "type": "number" }
]
}Common Patterns
API Request Validation
Validate API requests with UUID, email, and age constraints.
{
"type": "object",
"properties": {
"id": { "type": "string", "format": "uuid" },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 120 }
},
"required": ["id", "email"]
}Configuration File Validation
Validate nested configuration objects with database settings.
{
"type": "object",
"properties": {
"database": {
"type": "object",
"properties": {
"host": { "type": "string" },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 }
},
"required": ["host", "port"]
}
},
"required": ["database"]
}Best Practices
- Use descriptive property names - Choose clear, meaningful names for your schema properties
- Document your schemas - Add description fields to explain complex constraints
- Start simple, add constraints gradually - Begin with basic validation and add complexity as needed
- Use version control - Track schema changes alongside your code
- Test thoroughly - Validate both valid and invalid data to ensure your schema works correctly
Common Pitfalls
Over-validation
Avoid making schemas too strict. Allow flexibility where appropriate.
Missing required fields
Ensure all essential fields are marked as required.
Incorrect type definitions
Be precise with types (number vs integer, string vs enum).
Circular dependencies
Avoid circular references in your schemas.
Ignoring error messages
Pay attention to validation errors to understand what's failing.
Advanced Topics
- Schema composition - Combine schemas using allOf, anyOf, and oneOf for complex validation logic
- Custom keywords - Some validators support custom keywords for specialized validation
- Schema references - Use $ref to reference other schemas and avoid duplication
- Schema dereferencing - Resolve $ref references to create a single, complete schema
Security Considerations
Input validation
Always validate user input with schemas before processing.
Schema poisoning
Don't trust schemas from untrusted sources without review.
Resource limits
Be aware of potential denial-of-service attacks with deeply nested schemas.
Tools and Ecosystem
- Validators - Use this JSON Schema Validator for quick validation, or integrate libraries like Ajv (JavaScript), jsonschema (Python), or jsonschema (Java) in your applications
- Editors - Many IDEs have JSON Schema support for autocomplete and validation
- Generators - Generate schemas from existing data or generate code from schemas
- Documentation - Use tools like json-schema-doc to generate human-readable documentation from schemas