跳到主要内容

规范统一:JSON To JSON Schema — Numio

从 JSON 示例推断 JSON Schema(draft-07)。对于对象数组,会合并所有元素:在部分元素中缺失或为 null 的键不会列入 required。

根据抓取到的示例,为 API 响应或 webhook 载荷创建第一版校验 schema。

JSON

JSON Schema

适用场景

  • 根据抓取到的示例,为 API 响应或 webhook 载荷创建第一版校验 schema。
  • 生成供 Ajv、OpenAPI 或 JSON Schema 转 TypeScript/Zod 步骤使用的 schema。

使用方法

  1. 将 JSON 示例粘贴到左侧编辑器,或用加载文件按钮打开 UTF-8 文件;包含多条记录的数组能得到更准确的 required 列表。
  2. 查看 schema:单个对象中的每个键都是必填,在部分数组元素中缺失或为 null 的键为可选。
  3. 复制 schema,补充示例无法体现的约束,例如 format、enum、integer 和 minimum。

JSON 示例

[
  { "id": 1, "name": "Ada", "email": null },
  { "id": 2, "name": "Lin", "email": "lin@example.com" }
]

JSON Schema(draft-07)

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Generated schema for Root",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "id": {
        "type": "number"
      },
      "name": {
        "type": "string"
      },
      "email": {
        "type": "string"
      }
    },
    "required": [
      "id",
      "name"
    ]
  }
}

功能与限制

数字始终为 "type": "number";不会推断 integer、格式(email、date-time)、enum 和 pattern。title 始终为 "Generated schema for Root"。

在所有位置都为 null 的字段会得到空 schema {}。与其他值并存的 null 会被视为可选,而不是 null 类型。

[1, "x"] 这类混合类型数组会变为元组(items 列表加 additionalItems: false);空数组得到 items: {}。

由编译为 WebAssembly 的 json_typegen 在浏览器中生成。无效 JSON(包括末尾逗号)会显示 JSON 解析错误,42 这样的单个值没有结构,会被拒绝。

FAQ

输出的是哪个 JSON Schema 草案?

Draft-07,声明为 "$schema": "http://json-schema.org/draft-07/schema#"。不能选择 2019-09 或 2020-12。

如何判断可选字段?

只在同一数组的元素之间判断:在部分对象中缺失或为 null 的键不会列入 required。单个对象中的每个键都是必填。

根节点可以是 JSON 数组吗?

可以。根节点得到 "type": "array",元素合并为一个 items schema,如示例所示。

规范与参考资料