JSON Schema is a powerful tool for validating the structure and content of JSON documents. It provides a way to define the expected format of your JSON data, making validation more robust and documentation more clear. This guide introduces JSON Schema and shows how to use it effectively.
What is JSON Schema?
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It describes the structure of JSON data, specifying what properties are required, what types they should be, and any constraints they must satisfy.
Think of JSON Schema as a blueprint for your JSON data. Just as an architect uses a blueprint to ensure a building meets specifications, JSON Schema ensures your JSON data meets your application's requirements.
Basic Schema Structure
A JSON Schema is itself a JSON document that defines the rules for validating other JSON documents.
Simple Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}Valid JSON:
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}Schema Keywords
Type Validation
The type keyword specifies the data type for a value.
{
"type": "string", // "hello"
"type": "number", // 42, 3.14
"type": "integer", // 42
"type": "boolean", // true, false
"type": "object", // { "key": "value" }
"type": "array", // [1, 2, 3]
"type": "null" // null
}String Constraints
Control string length and format.
{
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[A-Za-z]+$",
"format": "email"
}Number Constraints
Set minimum and maximum values for numbers.
{
"type": "number",
"minimum": 0,
"maximum": 100,
"exclusiveMinimum": 0,
"multipleOf": 5
}Array Validation
Define array structure and constraints.
{
"type": "array",
"minItems": 1,
"maxItems": 10,
"uniqueItems": true,
"items": {
"type": "string"
}
}Object Validation
Define object properties and requirements.
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name"],
"additionalProperties": false
}Advanced Schema Features
Conditional Validation
Use if, then, and else for conditional validation.
{
"type": "object",
"properties": {
"country": { "type": "string" },
"postalCode": { "type": "string" }
},
"if": {
"properties": { "country": { "const": "US" } }
},
"then": {
"properties": {
"postalCode": { "pattern": "^\\d{5}(-\\d{4})?$" }
}
}
}References and Reuse
Use $ref to reference other schemas and avoid duplication.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"zipCode": { "type": "string" }
},
"required": ["street", "city"]
}
},
"type": "object",
"properties": {
"name": { "type": "string" },
"homeAddress": { "$ref": "#/definitions/address" },
"workAddress": { "$ref": "#/definitions/address" }
}
}Using JSON Schema with JSONLintPlus
While JSONLintPlus focuses on syntax validation, you can combine it with JSON Schema libraries for comprehensive validation.
JavaScript Example:
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer', minimum: 0 }
},
required: ['name']
};
const validate = ajv.compile(schema);
// First validate syntax with JSONLintPlus
const jsonString = '{"name": "John", "age": 30}';
let data;
try {
data = JSON.parse(jsonString);
} catch (error) {
console.error('Invalid JSON syntax');
return;
}
// Then validate against schema
const valid = validate(data);
if (!valid) {
console.error('Schema validation failed:', validate.errors);
} else {
console.log('JSON is valid!');
}Common Use Cases
API Request/Response Validation
Ensure API requests and responses conform to expected formats.
Configuration File Validation
Validate application configuration files at startup.
Data Import/Export Validation
Ensure imported data meets quality standards.
Form Data Validation
Validate form submissions before processing.
Best Practices
1. Start Simple
Begin with basic type validation and gradually add constraints as needed.
2. Use Descriptive Property Names
Choose clear, descriptive names for your schema properties.
3. Document Your Schemas
Add descriptions to your schemas to make them self-documenting.
{
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email",
"description": "User's email address for account verification"
}
}
}4. Version Your Schemas
Use schema versioning to maintain backward compatibility.
5. Test Your Schemas
Create comprehensive test cases for your schemas, including edge cases.
Schema Versions
JSON Schema has evolved through several versions (drafts). Always specify which version you're using.
| Draft | Schema URI | Key Features |
|---|---|---|
| Draft-04 | http://json-schema.org/draft-04/schema# | Basic validation features |
| Draft-06 | http://json-schema.org/draft-06/schema# | Format validation, constant values |
| Draft-07 | http://json-schema.org/draft-07/schema# | if/then/else, content validation |
| Draft 2019-09 | https://json-schema.org/draft/2019-09/schema | Unevaluated properties, dependent schemas |
| Draft 2020-12 | https://json-schema.org/draft/2020-12/schema | Latest features and improvements |
Conclusion
JSON Schema is a powerful tool for ensuring data quality and consistency in your applications. By defining clear schemas for your JSON data, you can catch errors early, improve API reliability, and create better documentation.
Start with basic schemas and gradually add complexity as your validation needs grow. Combine JSON Schema with syntax validation tools like JSONLintPlus for comprehensive JSON handling.