JSON Schema 完整指南 - 从入门到精通

1713 字
9 分钟
JSON Schema 完整指南 - 从入门到精通

引言#

JSON Schema 是一种基于 JSON 的格式,用于描述和验证 JSON 数据的结构。本完整指南将带您从入门到精通,全面掌握 JSON Schema 的语法、类型系统、验证规则和最佳实践。

目录#

  1. JSON Schema 基础
  2. 类型系统
  3. 验证关键字
  4. 组合关键字
  5. 格式规范
  6. 实战示例

JSON Schema 基础 {#basics}#

什么是 JSON Schema?#

JSON Schema 是一种描述 JSON 数据结构的规范,用于:

  • 验证:确保数据符合预期结构
  • 文档:自动生成数据字典
  • 测试:自动化数据验证测试
  • IDE 支持:智能提示和自动补全

Schema 基本结构#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "用户信息",
"description": "描述用户的基本信息",
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "用户 ID"
},
"name": {
"type": "string",
"description": "用户姓名"
},
"email": {
"type": "string",
"format": "email",
"description": "用户邮箱"
}
},
"required": ["id", "name", "email"]
}

元数据关键字#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/user.schema.json",
"title": "用户 Schema",
"description": "描述用户数据结构",
"default": {},
"examples": [
{
"id": 1,
"name": "John",
"email": "john@example.com"
}
],
"readOnly": true,
"writeOnly": false
}

$ref 引用#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"zip": { "type": "string" }
}
}
},
"type": "object",
"properties": {
"billing": { "$ref": "#/definitions/address" },
"shipping": { "$ref": "#/definitions/address" }
}
}

类型系统 {#types}#

基本类型#

{
"stringType": { "type": "string" },
"numberType": { "type": "number" },
"integerType": { "type": "integer" },
"booleanType": { "type": "boolean" },
"arrayType": { "type": "array" },
"objectType": { "type": "object" },
"nullType": { "type": "null" }
}

多类型#

{
"stringOrNumber": {
"type": ["string", "number"]
},
"nullable": {
"type": ["string", "null"]
}
}

String 类型详解#

{
"string": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[a-zA-Z]+$",
"format": "email"
}
}

常用 format 值:

  • email: 邮箱地址
  • uri: URL 地址
  • date: 日期 (YYYY-MM-DD)
  • date-time: 日期时间 (ISO 8601)
  • time: 时间
  • ipv4: IPv4 地址
  • ipv6: IPv6 地址
  • hostname: 主机名
  • uuid: UUID
  • uri-reference: URI 引用

Number 类型详解#

{
"number": {
"type": "number",
"minimum": 0,
"maximum": 100,
"exclusiveMinimum": 0,
"exclusiveMaximum": 100,
"multipleOf": 5
},
"integer": {
"type": "integer",
"minimum": 1,
"maximum": 10
}
}

Array 类型详解#

{
"array": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"maxItems": 10,
"uniqueItems": true,
"contains": {
"type": "string",
"minLength": 1
}
},
"tuple": {
"type": "array",
"items": [
{ "type": "string" },
{ "type": "number" },
{ "type": "boolean" }
],
"additionalItems": false
}
}

Object 类型详解#

{
"object": {
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "age"],
"additionalProperties": false,
"minProperties": 2,
"maxProperties": 5,
"propertyNames": {
"type": "string",
"pattern": "^[a-z]+$"
}
}
}

验证关键字 {#validation}#

数值验证#

{
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150,
"exclusiveMinimum": 0,
"exclusiveMaximum": 150,
"multipleOf": 1
},
"price": {
"type": "number",
"minimum": 0,
"maximum": 9999.99,
"multipleOf": 0.01
}
}

字符串验证#

{
"username": {
"type": "string",
"minLength": 3,
"maxLength": 20,
"pattern": "^[a-zA-Z0-9_]+$"
},
"description": {
"type": "string",
"minLength": 10,
"maxLength": 500
},
"email": {
"type": "string",
"format": "email"
}
}

数组验证#

{
"tags": {
"type": "array",
"minItems": 1,
"maxItems": 10,
"uniqueItems": true,
"items": {
"type": "string",
"minLength": 1
},
"contains": {
"enum": ["important"]
}
}
}

对象验证#

{
"user": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"email": { "type": "string", "format": "email" }
},
"required": ["id", "name", "email"],
"additionalProperties": false,
"minProperties": 3,
"maxProperties": 10
}
}

Enum 验证#

{
"status": {
"type": "string",
"enum": ["active", "inactive", "pending"]
},
"priority": {
"type": "integer",
"enum": [1, 2, 3, 4, 5]
},
"role": {
"type": "string",
"enum": ["user", "admin", "moderator"]
}
}

Const 验证(Draft-06+)#

{
"version": {
"const": "1.0.0"
},
"type": {
"const": "premium"
}
}

组合关键字 {#composition}#

allOf(与)#

{
"allOf": [
{
"type": "object",
"properties": {
"name": { "type": "string" }
}
},
{
"type": "object",
"properties": {
"age": { "type": "integer" }
},
"required": ["age"]
}
]
}
// 结果:必须同时包含 name 和 age,且 age 必填

anyOf(或)#

{
"anyOf": [
{
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" }
}
},
{
"type": "object",
"properties": {
"phone": { "type": "string", "pattern": "^\\+?[0-9]+$" }
}
}
]
}
// 结果:可以是 email 对象或 phone 对象

oneOf(异或)#

{
"oneOf": [
{
"type": "object",
"properties": {
"credit_card": { "type": "string" }
}
},
{
"type": "object",
"properties": {
"paypal": { "type": "string", "format": "email" }
}
}
]
}
// 结果:只能是信用卡或 PayPal,不能同时

not(非)#

{
"not": {
"type": "object",
"properties": {
"status": { "const": "deleted" }
}
}
}
// 结果:不能是 status 为 deleted 的对象

if/then/else(条件)#

{
"type": "object",
"properties": {
"country": { "type": "string" },
"postal_code": { "type": "string" }
},
"if": {
"properties": {
"country": { "const": "US" }
}
},
"then": {
"properties": {
"postal_code": { "pattern": "^\\d{5}$" }
}
},
"else": {
"properties": {
"postal_code": { "pattern": "^[A-Z0-9]+$" }
}
}
}
// 结果:美国邮编 5 位数字,其他国家字母数字组合

格式规范 {#formats}#

内置格式#

{
"formats": {
"email": { "type": "string", "format": "email" },
"uri": { "type": "string", "format": "uri" },
"date": { "type": "string", "format": "date" },
"date-time": { "type": "string", "format": "date-time" },
"time": { "type": "string", "format": "time" },
"ipv4": { "type": "string", "format": "ipv4" },
"ipv6": { "type": "string", "format": "ipv6" },
"hostname": { "type": "string", "format": "hostname" },
"uuid": { "type": "string", "format": "uuid" },
"uri-reference": { "type": "string", "format": "uri-reference" },
"iri": { "type": "string", "format": "iri" },
"iri-reference": { "type": "string", "format": "iri-reference" },
"regex": { "type": "string", "format": "regex" },
"json-pointer": { "type": "string", "format": "json-pointer" },
"relative-json-pointer": { "type": "string", "format": "relative-json-pointer" }
}
}

自定义格式#

{
"phone": {
"type": "string",
"pattern": "^\\+?[0-9\\-\\s]+$",
"description": "Phone number in international format"
},
"color": {
"type": "string",
"pattern": "^#[0-9A-Fa-f]{6}$",
"description": "Hex color code"
}
}

实战示例 {#examples}#

示例 1:用户 Schema#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "用户",
"description": "描述用户账户信息",
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "用户唯一标识",
"minimum": 1
},
"username": {
"type": "string",
"description": "用户名",
"minLength": 3,
"maxLength": 20,
"pattern": "^[a-zA-Z0-9_]+$"
},
"email": {
"type": "string",
"format": "email",
"description": "用户邮箱"
},
"profile": {
"type": "object",
"properties": {
"firstName": { "type": "string" },
"lastName": { "type": "string" },
"age": { "type": "integer", "minimum": 0 },
"bio": { "type": "string", "maxLength": 500 }
},
"required": ["firstName", "lastName"]
},
"roles": {
"type": "array",
"items": {
"type": "string",
"enum": ["user", "admin", "moderator"]
},
"uniqueItems": true,
"minItems": 1
},
"createdAt": {
"type": "string",
"format": "date-time"
},
"isActive": {
"type": "boolean",
"default": true
}
},
"required": ["id", "username", "email", "createdAt"],
"additionalProperties": false
}

示例 2:API 响应 Schema#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "API 响应",
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["success", "error"]
},
"data": {
"oneOf": [
{
"type": "object",
"properties": {
"items": {
"type": "array",
"items": { "$ref": "#/definitions/item" }
},
"total": { "type": "integer" },
"page": { "type": "integer" }
}
},
{
"type": "object",
"properties": {
"message": { "type": "string" },
"code": { "type": "string" }
}
}
]
},
"timestamp": {
"type": "string",
"format": "date-time"
}
},
"required": ["status", "data", "timestamp"],
"definitions": {
"item": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"price": { "type": "number", "minimum": 0 }
},
"required": ["id", "name", "price"]
}
}
}

示例 3:配置文件 Schema#

{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "应用配置",
"type": "object",
"properties": {
"database": {
"type": "object",
"properties": {
"host": { "type": "string", "format": "hostname" },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 },
"name": { "type": "string", "minLength": 1 },
"user": { "type": "string" },
"password": { "type": "string" },
"ssl": { "type": "boolean", "default": false }
},
"required": ["host", "port", "name", "user", "password"]
},
"server": {
"type": "object",
"properties": {
"host": { "type": "string", "default": "0.0.0.0" },
"port": { "type": "integer", "default": 3000 },
"workers": { "type": "integer", "minimum": 1, "default": 4 }
},
"required": ["port"]
},
"features": {
"type": "object",
"properties": {
"enableCache": { "type": "boolean", "default": true },
"enableLogs": { "type": "boolean", "default": true },
"maxConnections": { "type": "integer", "default": 100 }
}
},
"logging": {
"type": "object",
"properties": {
"level": {
"type": "string",
"enum": ["debug", "info", "warn", "error"],
"default": "info"
},
"file": { "type": "string" },
"maxSize": { "type": "string", "pattern": "^\\d+[KMGT]B$" }
}
}
},
"required": ["database", "server"]
}

总结#

本指南涵盖了 JSON Schema 的核心内容:

  1. 基础:元数据、$ref 引用
  2. 类型:string、number、integer、boolean、array、object、null
  3. 验证:数值、字符串、数组、对象、enum、const
  4. 组合:allOf、anyOf、oneOf、not、if/then/else
  5. 格式:内置格式和自定义格式
  6. 实战:用户、API 响应、配置文件

掌握这些知识,您可以设计和验证任何 JSON 数据结构!

相关资源:

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

最后更新于 2026-01-15,距今已过 263 天

部分内容可能已过时

公告
🎉 已升级 2.0 版本,欢迎使用。
分类
标签
站点统计
文章
194
分类
23
标签
735
总字数
327,233
运行时长
0 天
最后活动
0 天前

目录