JSON Schema Validation Guide: Data Validation & Doc Generation
JSON Schema: A Contract for Your Data
JSON Schema is a structure-definition language for JSON data — similar to what TypeScript is to JavaScript, but designed for runtime validation and cross-language scenarios.
| Use Case | Description |
|---|---|
| Data validation | Validate API requests/responses |
| Documentation generation | Auto-generate API docs |
| IDE hints | Smart autocomplete in VS Code |
| Mock data | Auto-generate test data |
| Config validation | package.json, tsconfig.json, etc. |
1. Basic Types
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1, "maxLength": 100 },
"age": { "type": "integer", "minimum": 0, "maximum": 150 },
"email": { "type": "string", "format": "email" },
"isActive": { "type": "boolean" },
"score": { "type": "number", "minimum": 0, "maximum": 100 },
"tags": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
}
},
"required": ["name", "email"],
"additionalProperties": false
}
Built-in Formats
| format | Matching Rule | Example |
|---|---|---|
email |
RFC 5322 | user@example.com |
uri |
URI | https://example.com |
date |
ISO 8601 date | 2026-06-02 |
time |
ISO 8601 time | 14:30:00 |
date-time |
ISO 8601 date-time | 2026-06-02T14:30:00Z |
ipv4 |
IPv4 address | 192.168.1.1 |
ipv6 |
IPv6 address | ::1 |
uuid |
UUID | 550e8400-e29b-41d4-a716-446655440000 |
hostname |
Hostname | example.com |
2. Advanced Patterns
Nested Objects
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"profile": {
"type": "object",
"properties": {
"avatar": { "type": "string", "format": "uri" },
"bio": { "type": "string", "maxLength": 200 }
}
}
}
}
}
}
Enums and Union Types
{
"status": {
"type": "string",
"enum": ["pending", "active", "completed", "cancelled"]
},
"id": {
"oneOf": [
{ "type": "string", "format": "uuid" },
{ "type": "integer", "minimum": 1 }
]
}
}
Conditional Validation
{
"type": "object",
"properties": {
"paymentMethod": { "type": "string", "enum": ["credit_card", "bank_transfer"] },
"cardNumber": { "type": "string" },
"bankAccount": { "type": "string" }
},
"if": {
"properties": { "paymentMethod": { "const": "credit_card" } }
},
"then": {
"required": ["cardNumber"],
"properties": { "cardNumber": { "pattern": "^\\d{16}$" } }
},
"else": {
"required": ["bankAccount"]
}
}
Regex Patterns
{
"phone": { "type": "string", "pattern": "^1[3-9]\\d{9}$" },
"postalCode": { "type": "string", "pattern": "^\\d{6}$" },
"slug": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" }
}
3. $ref and Reusable Definitions
{
"$defs": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"zipCode": { "type": "string", "pattern": "^\\d{6}$" }
},
"required": ["street", "city", "zipCode"]
}
},
"type": "object",
"properties": {
"homeAddress": { "$ref": "#/$defs/address" },
"workAddress": { "$ref": "#/$defs/address" }
}
}
4. Runtime Validation
Ajv (The Fastest Validator)
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true, strict: false });
const schema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'integer', minimum: 0 },
},
required: ['name', 'age'],
};
const validate = ajv.compile(schema);
const valid = validate({ name: '张三', age: 25 });
if (!valid) {
console.log(validate.errors);
// [{ keyword: 'minimum', dataPath: '/age', message: 'must be >= 0' }]
}
Zod (TypeScript-First)
import { z } from 'zod';
const UserSchema = z.object({
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150),
email: z.string().email(),
tags: z.array(z.string()).min(1).max(10),
});
// Automatic type inference
type User = z.infer<typeof UserSchema>;
// Validation
const result = UserSchema.safeParse(input);
if (result.success) {
console.log(result.data); // Type-safe
} else {
console.log(result.error.issues);
}
5. IDE Autocomplete
VS Code Configuration
// .vscode/settings.json
{
"json.schemas": [
{
"fileMatch": ["/config/*.json"],
"url": "./schemas/config-schema.json"
},
{
"fileMatch": ["package.json"],
"url": "https://json.schemastore.org/package"
}
]
}
Referencing a Schema in JSON Files
{
"$schema": "./schemas/config-schema.json",
"name": "my-project"
// IDE autocomplete and error hints
}
Schema Store
Schema Store provides 400+ common JSON Schemas:
- package.json
- tsconfig.json
- .eslintrc.json
- docker-compose.json
- GitHub Actions workflows
6. Generating a Schema from JSON
Using the Tool
- Open the JSON Formatter
- Paste your JSON data
- Click "Generate Schema"
- Types, enums, and ranges are inferred automatically
Command-Line Tools
# Using json-schema-generator
npx json-schema-generator sample.json -o schema.json
# Using quicktype
npx quicktype sample.json -o schema.json --lang schema
7. Mock Data Generation
import { faker } from '@faker-js/faker';
// Generate mock data based on a schema
function generateMock(schema) {
if (schema.type === 'string') {
if (schema.format === 'email') return faker.internet.email();
if (schema.format === 'uri') return faker.internet.url();
if (schema.enum) return faker.helpers.arrayElement(schema.enum);
return faker.lorem.word();
}
if (schema.type === 'integer') return faker.number.int(schema);
if (schema.type === 'boolean') return faker.datatype.boolean();
if (schema.type === 'array') {
return Array.from({ length: 3 }, () => generateMock(schema.items));
}
if (schema.type === 'object') {
const result = {};
for (const [key, propSchema] of Object.entries(schema.properties)) {
result[key] = generateMock(propSchema);
}
return result;
}
}
8. Best Practices
- Always declare
$schema: Pin the draft version to avoid ambiguity - Use
additionalProperties: false: Reject undefined fields - Use
$defs+$ref: Reuse common structures - Prefer
formatover hand-written patterns: More readable, and validators handle it automatically - Integrate validation into CI: Ensure API responses always conform to the schema
- Version your schemas: Keep them in sync with API versions and support backward-compatibility checks
#JSON Schema#数据校验#Ajv#Zod#API