JSON Schema 完整指南 - 从入门到精通
1713 字
9 分钟
JSON Schema 完整指南 - 从入门到精通
引言
JSON Schema 是一种基于 JSON 的格式,用于描述和验证 JSON 数据的结构。本完整指南将带您从入门到精通,全面掌握 JSON Schema 的语法、类型系统、验证规则和最佳实践。
目录
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: UUIDuri-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 的核心内容:
- 基础:元数据、$ref 引用
- 类型:string、number、integer、boolean、array、object、null
- 验证:数值、字符串、数组、对象、enum、const
- 组合:allOf、anyOf、oneOf、not、if/then/else
- 格式:内置格式和自定义格式
- 实战:用户、API 响应、配置文件
掌握这些知识,您可以设计和验证任何 JSON 数据结构!
相关资源:
- JSON Schema Generator 工具 - 在线生成 Schema
- JSON Schema 最佳实践 - 设计技巧
- JSON Schema 常见问题 - 故障排除
- JSON Schema 实战示例 - 实际案例
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
最后更新于 2026-01-15,距今已过 263 天
部分内容可能已过时
相关文章 智能推荐
1
JSON Schema 实战示例 - 从真实场景学习
JSON 工具 通过实际案例学习 JSON Schema 设计。包含 REST API、表单验证、配置文件、微服务、数据管道等真实场景的完整 Schema 示例。
2
JSON Schema 常见问题及解决方案 - 故障排除指南
JSON 工具 解决 JSON Schema 使用中的常见问题。学习验证错误、$ref 引用、类型验证、格式问题等故障排除技巧和解决方案。
3
JSON Schema 验证集成指南与工作流自动化
技术教程 学习如何将 JSON Schema 验证集成到 Pre-commit Hook、CI Pipeline、Express 中间件和 MongoDB 中,实现全链路数据质量保障。
4
JSON Schema 最佳实践 - 规范设计与性能优化
JSON 工具 掌握 JSON Schema 最佳实践,学习 Schema 设计原则、复用技巧、性能优化、错误处理、版本管理等实战经验。提升 Schema 可维护性和性能。
5
星点HTTP工具完整指南 - 11个在线HTTP请求调试工具导航(2026)
HTTP工具 星点HTTP工具系列完整指南:HTTP请求测试、状态码查询、Header解析/生成、请求转cURL、cURL解析、cURL转代码、Cookie/Set-Cookie解析、CORS检测/生成、Content-Type/MIME查询等 11 个在线工具一站式导航,全部本地处理不上传。
随机文章 随机推荐