JSON Schema 验证完全指南:数据校验、文档生成与代码提示一体化
JSON Schema:数据的契约
JSON Schema 是 JSON 数据的结构定义语言——类似 TypeScript 之于 JavaScript,但适用于运行时验证和跨语言场景。
| 用途 | 说明 |
|---|---|
| 数据验证 | API 请求/响应校验 |
| 文档生成 | 自动生成 API 文档 |
| IDE 提示 | VS Code 智能补全 |
| Mock 数据 | 自动生成测试数据 |
| 配置校验 | package.json、tsconfig.json 等 |
一、基础类型
{
"$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
}
内置格式
| format | 匹配规则 | 示例 |
|---|---|---|
email |
RFC 5322 | user@example.com |
uri |
URI | https://example.com |
date |
ISO 8601 日期 | 2026-06-02 |
time |
ISO 8601 时间 | 14:30:00 |
date-time |
ISO 8601 日期时间 | 2026-06-02T14:30:00Z |
ipv4 |
IPv4 地址 | 192.168.1.1 |
ipv6 |
IPv6 地址 | ::1 |
uuid |
UUID | 550e8400-e29b-41d4-a716-446655440000 |
hostname |
主机名 | example.com |
二、高级模式
嵌套对象
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"profile": {
"type": "object",
"properties": {
"avatar": { "type": "string", "format": "uri" },
"bio": { "type": "string", "maxLength": 200 }
}
}
}
}
}
}
枚举与联合类型
{
"status": {
"type": "string",
"enum": ["pending", "active", "completed", "cancelled"]
},
"id": {
"oneOf": [
{ "type": "string", "format": "uuid" },
{ "type": "integer", "minimum": 1 }
]
}
}
条件验证
{
"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"]
}
}
正则模式
{
"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]+)*$" }
}
三、$ref 与定义复用
{
"$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" }
}
}
四、运行时验证
Ajv(最快验证器)
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 优先)
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),
});
// 类型自动推导
type User = z.infer<typeof UserSchema>;
// 验证
const result = UserSchema.safeParse(input);
if (result.success) {
console.log(result.data); // 类型安全
} else {
console.log(result.error.issues);
}
五、IDE 智能提示
VS Code 配置
// .vscode/settings.json
{
"json.schemas": [
{
"fileMatch": ["/config/*.json"],
"url": "./schemas/config-schema.json"
},
{
"fileMatch": ["package.json"],
"url": "https://json.schemastore.org/package"
}
]
}
JSON 文件中引用 Schema
{
"$schema": "./schemas/config-schema.json",
"name": "my-project"
// IDE 自动补全、错误提示
}
Schema Store
Schema Store 提供 400+ 常见 JSON Schema:
- package.json
- tsconfig.json
- .eslintrc.json
- docker-compose.json
- GitHub Actions workflows
六、从 JSON 生成 Schema
使用工具库
- 打开 JSON 格式化工具
- 粘贴 JSON 数据
- 点击"生成 Schema"
- 自动推导类型、枚举、范围
命令行工具
# 使用 json-schema-generator
npx json-schema-generator sample.json -o schema.json
# 使用 quicktype
npx quicktype sample.json -o schema.json --lang schema
七、Mock 数据生成
import { faker } from '@faker-js/faker';
// 基于 Schema 生成 Mock 数据
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;
}
}
八、最佳实践
- 始终声明
$schema:指定 Draft 版本,避免歧义 - 用
additionalProperties: false:禁止未定义的字段 - 用
$defs+$ref:复用通用结构 - 用
format而非手写 pattern:更可读,验证器自动处理 - CI 集成验证:确保 API 响应始终符合 Schema
- Schema 版本管理:与 API 版本同步,支持向后兼容检查
#JSON Schema#数据校验#Ajv#Zod#API