JSON Schema
新 — Zod 4 引入了一项新功能:原生 JSON Schema 转换。JSON Schema 是一种用于描述 JSON 结构(使用 JSON)的标准。它被广泛用于 OpenAPI 定义和为 AI 定义 结构化输出。
z.fromJSONSchema()
实验性 — z.fromJSONSchema() 函数是实验性的,尚未被视为 Zod 稳定 API 的一部分。在未来的版本中,它可能会进行实现上的更改。
Zod 提供 z.fromJSONSchema() 来将 JSON 模式转换为 Zod 模式。
🌐 Zod provides z.fromJSONSchema() to convert a JSON Schema into a Zod schema.
z.toJSONSchema()
要将 Zod 模式转换为 JSON 模式,请使用 z.toJSONSchema() 函数。
🌐 To convert a Zod schema to JSON Schema, use the z.toJSONSchema() function.
所有模式和检查都已转换为其最接近的 JSON 模式等效项。某些类型没有对应的类比,无法合理表示。有关处理这些情况的更多信息,请参见下面的 unrepresentable 部分。
🌐 All schema & checks are converted to their closest JSON Schema equivalent. Some types have no analog and cannot be reasonably represented. See the unrepresentable section below for more information on handling these cases.
第二个参数可用于自定义转换逻辑。
🌐 A second argument can be used to customize the conversion logic.
以下是每个支持参数的快速参考。每个参数的详细说明如下。
🌐 Below is a quick reference for each supported parameter. Each one is explained in more detail below.
io
某些模式类型具有不同的输入和输出类型,例如 ZodPipe、ZodDefault 以及被强制转换的原始类型。默认情况下,z.toJSONSchema 的结果表示输出类型;使用 "io": "input" 可以提取输入类型。
🌐 Some schema types have different input and output types, e.g. ZodPipe, ZodDefault, and coerced primitives. By default, the result of z.toJSONSchema represents the output type; use "io": "input" to extract the input type instead.
target
要设置目标 JSON Schema 版本,请使用 target 参数。默认情况下,Zod 将使用 Draft 2020-12 版本。
🌐 To set the target JSON Schema version, use the target parameter. By default, Zod will target Draft 2020-12.
metadata
如果你还没有阅读过,请查看 Metadata and registries 页面,以了解在 Zod 中存储元数据的相关背景。
在 Zod 中,元数据存储在注册表中。Zod 导出一个全局注册表 z.globalRegistry,可以用来存储常见的元数据字段,如 id、title、description 和 examples。
🌐 In Zod, metadata is stored in registries. Zod exports a global registry z.globalRegistry that can be used to store common metadata fields like id, title, description, and examples.
所有元数据字段都会被复制到生成的 JSON Schema 中。
🌐 All metadata fields get copied into the resulting JSON Schema.
unrepresentable
以下 API 无法在 JSON Schema 中表示。默认情况下,如果遇到它们,Zod 将抛出错误。尝试转换为 JSON Schema 是不可靠的;你应该修改你的模式,因为它们在 JSON 中没有等效项。如果遇到这些,将抛出错误。
🌐 The following APIs are not representable in JSON Schema. By default, Zod will throw an error if they are encountered. It is unsound to attempt a conversion to JSON Schema; you should modify your schemas as they have no equivalent in JSON. An error will be thrown if any of these are encountered.
默认情况下,如果遇到任何这些情况,Zod 都会抛出错误。
🌐 By default, Zod will throw an error if any of these are encountered.
你可以通过将 unrepresentable 选项设置为 "any" 来更改此行为。这将把任何无法表示的类型转换为 {}(相当于 JSON Schema 中的 unknown)。
🌐 You can change this behavior by setting the unrepresentable option to "any". This will convert any unrepresentable types to {} (the equivalent of unknown in JSON Schema).
cycles
如何处理循环。如果在 z.toJSONSchema() 遍历模式时遇到循环,它将使用 $ref 表示。
🌐 How to handle cycles. If a cycle is encountered as z.toJSONSchema() traverses the schema, it will be represented using $ref.
如果你想改为抛出错误,请将 cycles 选项设置为 "throw"。
🌐 If instead you want to throw an error, set the cycles option to "throw".
reused
如何处理在同一模式中多次出现的模式。默认情况下,Zod 会将这些模式内联。
🌐 How to handle schemas that occur multiple times in the same schema. By default, Zod will inline these schemas.
相反,你可以将 reused 选项设置为 "ref",以将这些模式提取到 $defs。
🌐 Instead you can set the reused option to "ref" to extract these schemas into $defs.
override
要定义一些自定义覆盖逻辑,请使用 override。提供的回调可以访问原始的 Zod 模式和默认的 JSON Schema。此函数应直接修改 ctx.jsonSchema。
🌐 To define some custom override logic, use override. The provided callback has access to the original Zod schema and the default JSON Schema. This function should directly modify ctx.jsonSchema.
请注意,在调用此函数之前,不可表示的类型将抛出 Error。如果你试图为不可表示的类型定义自定义行为,你需要同时设置 unrepresentable: "any" 和 override。
🌐 Note that unrepresentable types will throw an Error before this function is called. If you are trying to define custom behavior for an unrepresentable type, you'll need to set the unrepresentable: "any" alongside override.
转换
🌐 Conversion
以下是关于 Zod JSON Schema 转换逻辑的更多详细信息。
🌐 Below are additional details regarding Zod's JSON Schema conversion logic.
字符串格式
🌐 String formats
Zod 将以下模式类型转换为等效的 JSON 模式 format:
🌐 Zod converts the following schema types to the equivalent JSON Schema format:
这些模式通过 contentEncoding 支持:
🌐 These schemas are supported via contentEncoding:
所有其他字符串格式都通过 pattern 支持:
🌐 All other string formats are supported via pattern:
数字类型
🌐 Numeric types
Zod 将以下数字类型转换为 JSON Schema:
🌐 Zod converts the following numeric types to JSON Schema:
对象模式
🌐 Object schemas
默认情况下,z.object() 模式包含 additionalProperties: "false"。这准确地反映了 Zod 的默认行为,因为普通的 z.object() 模式会移除额外的属性。
🌐 By default, z.object() schemas contain additionalProperties: "false". This is an accurate representation of Zod's default behavior, as plain z.object() schema strip additional properties.
在 "input" 模式下转换为 JSON Schema 时,additionalProperties 未设置。有关更多信息,请参阅 io 文档。
🌐 When converting to JSON Schema in "input" mode, additionalProperties is not set. See the io docs for more information.
相比之下:
🌐 By contrast:
z.looseObject()永远不会设置additionalProperties: falsez.strictObject()将始终设置additionalProperties: false
文件模式
🌐 File schemas
Zod 将 z.file() 转换为以下适用于 OpenAPI 的模式:
🌐 Zod converts z.file() to the following OpenAPI-friendly schema:
大小和 MIME 检查也表示为:
🌐 Size and MIME checks are also represented:
可空性
🌐 Nullability
Zod 在 JSON Schema 中将 z.null() 转换为 { type: "null" }。
🌐 Zod converts z.null() to { type: "null" } in JSON Schema.
请注意,z.undefined() 在 JSON Schema 中无法表示(参见 下文)。
🌐 Note that z.undefined() is unrepresentable in JSON Schema (see below).
同样,nullable 是通过与 null 的联合表示的:
🌐 Similarly, nullable is represented via a union with null:
可选模式按原样表示,尽管它们带有 optional 注解。
🌐 Optional schemas are represented as-is, though they are decorated with an optional annotation.
注册表
🌐 Registries
将一个模式传入 z.toJSONSchema() 将返回一个自包含的 JSON 模式。
🌐 Passing a schema into z.toJSONSchema() will return a self-contained JSON Schema.
在其他情况下,你可能有一组 Zod 模式,你希望使用多个互相关联的 JSON 模式来表示,可能用于写入 .json 文件并从 Web 服务器提供服务。
🌐 In other cases, you may have a set of Zod schemas you'd like to represent using multiple interlinked JSON Schemas, perhaps to write to .json files and serve from a web server.
要实现这一点,你可以将一个 registry 传递给 z.toJSONSchema()。
🌐 To achieve this, you can pass a registry into z.toJSONSchema().
重要 — 所有模式在注册表中都应注册 id 属性!任何没有 id 的模式将被忽略。
默认情况下,$ref URI 是像 "User" 这样的简单相对路径。要将这些变为绝对 URI,请使用 uri 选项。此选项需要一个将 id 转换为完全限定 URI 的函数。
🌐 By default, the $ref URIs are simple relative paths like "User". To make these absolute URIs, use the uri option. This expects a function that converts an id to a fully-qualified URI.

