JSON Schema: How to Validate Your JSON Data
JSON Schema is a powerful tool for validating the structure and content of JSON data. Learn how to define schemas and ensure your data meets your requirements.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It describes the structure of your data, including required fields, data types, formats, and constraints.
Basic Schema Structure
A JSON Schema is itself a JSON document that describes what valid data should look like.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
},
"required": ["name", "email"]
}Common Schema Keywords
Type Validation
The type keyword specifies the data type: string, number, integer, boolean, array, object, or null.
String Constraints
{
"type": "string",
"minLength": 2,
"maxLength": 100,
"pattern": "^[A-Za-z]+$"
}Number Constraints
{
"type": "number",
"minimum": 0,
"maximum": 100,
"multipleOf": 0.01
}Array Validation
{
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}Validation Libraries
Popular libraries for validating JSON against schemas include:
- Ajv - Fast JSON validator for JavaScript/TypeScript
- jsonschema - Python implementation
- everit-org/json-schema - Java validator
- Zod - TypeScript-first schema validation (alternative approach)
Example: Using Ajv in JavaScript
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = new Ajv();
addFormats(ajv);
const schema = {
type: "object",
properties: {
email: { type: "string", format: "email" },
age: { type: "integer", minimum: 18 }
},
required: ["email"]
};
const validate = ajv.compile(schema);
const data = { email: "test@example.com", age: 25 };
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}Best Practices
- Start with simple schemas and add complexity as needed
- Use descriptive titles and descriptions for documentation
- Define reusable schemas with
$ref - Validate early in your data pipeline
- Include meaningful error messages for users
Conclusion
JSON Schema provides a standardized way to validate JSON data, improving data quality and reducing bugs. Whether you're building APIs, configuration files, or data pipelines, schema validation is an essential tool in your development toolkit.