← 返回博客

什么是 JSON Schema,如何使用

2026-04-09 · 5 分钟阅读

JSON Schema 的定义

JSON Schema 是一种用于描述和验证 JSON 数据结构的标准规范。简单来说,它是用 JSON 编写的"合同",定义了某个 JSON 数据应该长什么样——哪些字段必须存在、各字段应该是什么类型、值的范围限制等。

JSON Schema 本身也是一个 JSON 对象,通过特定的关键字来描述规则。例如,"type": "string" 表示某个值必须是字符串,"required": ["name", "age"] 表示这两个字段是必填项。

一个完整的 JSON Schema 示例

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/user.schema.json",
  "title": "User",
  "description": "A user in the system",
  "type": "object",
  "required": ["id", "name", "email"],
  "properties": {
    "id": {
      "type": "integer",
      "minimum": 1,
      "description": "Unique user ID"
    },
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "tags": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true
    }
  },
  "additionalProperties": false
}

常用 JSON Schema 关键字

JSON Schema 的版本

JSON Schema 有多个版本(草案),不同版本的语法和支持的关键字略有差异:Draft 4(2013)是最广泛支持的版本,大多数验证库都支持;Draft 6/7(2016/2018)增加了 containsconstif/then/else 等新特性;Draft 2019-09 和 2020-12 是最新标准,增加了更多高级特性。

在 Schema 中通过 $schema 字段声明使用的版本,让验证工具知道应该使用哪套规则解析 Schema。

JSON Schema 在实际开发中的应用

API 开发中的应用:在 OpenAPI(Swagger)规范中,请求和响应的数据结构就是用 JSON Schema 描述的;后端框架(如 Fastify、FastAPI)可以直接用 JSON Schema 对请求数据进行自动验证,减少重复的手工验证代码;前端表单验证库(如 react-jsonschema-form)可以根据 JSON Schema 自动生成表单界面和验证规则。

配置文件支持:VS Code 通过 JSON Schema 为 package.jsontsconfig.json.eslintrc.json 等配置文件提供智能提示和实时错误检查,这就是为什么在 VS Code 中编辑这些文件时会有自动补全和错误高亮。

$ref 和 $defs:Schema 复用

对于复杂项目,同一个数据结构可能在多处使用,JSON Schema 提供了 $ref(引用)机制来复用 Schema 定义,避免重复:

{
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "street": {"type": "string"},
        "city": {"type": "string"}
      }
    }
  },
  "type": "object",
  "properties": {
    "homeAddress": {"$ref": "#/$defs/address"},
    "workAddress": {"$ref": "#/$defs/address"}
  }
}

验证库推荐

立即免费使用相关工具

免费使用 →