JSON Schema

JSON 教程 · 第 7 章 · 7 次浏览

JSON Schema 是描述 JSON 数据结构的规范:它本身是 JSON,用来校验"另一份 JSON 是否符合要求"。就像数据库的表结构约束数据一样。

用途

  • 接口文档:描述请求/响应结构
  • 表单校验:根据 schema 自动生成校验逻辑
  • 配置校验:验证配置文件字段是否正确

常用关键字

type(类型)、properties(属性定义)、required(必填)、enum(枚举值)、minimum/maximum(数字范围)、minLength/maxLength(字符串长度)、items(数组元素)。

代码示例

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": ["name", "age"],
    "properties": {
        "name": { "type": "string", "minLength": 2, "maxLength": 20 },
        "age": { "type": "integer", "minimum": 0, "maximum": 150 },
        "email": { "type": "string", "format": "email" },
        "role": { "enum": ["user", "admin"] },
        "tags": {
            "type": "array",
            "items": { "type": "string" }
        }
    }
}