开放标准:JSON Schema To OpenAPI规范 — Numio
将 JSON Schema(draft-04 及更高版本)转换为 OpenAPI 3.0 Schema Object。包含 "null" 的 type 数组会变为 "nullable: true",const 变为只有一项的 enum,examples 变为单个 example。
你用 draft-07 schema 校验请求数据,需要在 OpenAPI 3.0 文档的 components/schemas 下使用同一个模型。
适用场景
- 你用 draft-07 schema 校验请求数据,需要在 OpenAPI 3.0 文档的 components/schemas 下使用同一个模型。
- 你的 OpenAPI 3.0 工具不接受 "type": ["string", "null"],需要改写可为空的字段。
使用方法
- 将 JSON Schema 粘贴到 JSON Schema 面板。它必须是有效的 JSON,因为页面会在发送前先解析。
- schema 会被提交到 /api/json-schema-to-openapi-schema,在服务器上转换;面板中会显示相应提示。
- 从 Open API Schema 面板复制结果,放到 OpenAPI 文件的 components/schemas 下。
JSON Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"kind": { "const": "invoice" },
"total": { "type": ["number", "null"], "exclusiveMinimum": 0 },
"notes": { "type": "string", "examples": ["Net 30"] }
},
"required": ["kind"]
}OpenAPI 3.0 Schema Object
{
"type": "object",
"properties": {
"kind": {
"enum": [
"invoice"
]
},
"total": {
"type": "number",
"exclusiveMinimum": true,
"nullable": true,
"minimum": 0
},
"notes": {
"type": "string",
"example": "Net 30"
}
},
"required": [
"kind"
]
}功能与限制
页面会把输入发送到服务器路由(/api/json-schema-to-openapi-schema)进行转换,并不只在浏览器中处理。Next.js API 路由默认接受最大 1 MB 的请求体。
$schema 关键字会被移除。数值形式的 exclusiveMinimum/exclusiveMaximum 会改写为 OpenAPI 3.0 的形式:minimum/maximum 加一个布尔标志。
$ref 的值保持原样,definitions 不会移到 components/schemas,因此需要自行修正引用路径。
目标版本是 OpenAPI 3.0。OpenAPI 3.1 已直接使用 JSON Schema,通常无需转换。
FAQ
可为空的类型如何转换?
像 ["number", "null"] 这样的 type 数组会变为 "type": "number" 加 "nullable": true,如示例所示。
会解析 $ref 引用吗?
不会。页面不做解引用;"$ref": "#/definitions/Tag" 和 definitions 块会原样保留。
const 和 examples 会怎样处理?
const 变为只有一个值的 enum,examples 数组被替换为取自其第一项的单个 example。