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