On this page
Introduction
Sometimes you are interested in generating a JSON schema from a schema definition.
import * as z from "zod";
export const postSchema = z.object({ id: z.uuid(), authorId: z.string(), title: z.string(), content: z.string().nullable(), createdAt: z.date(), updatedAt: z.date().nullable(), published: z.date().nullable(),});
export type Post = z.infer<typeof postSchema>;Zod provides z.fromJSONSchema() to convert a JSON Schema into a Zod schema.
const jsonSchema = z.toJSONSchema(postSchema);console.log(jsonSchema);{ "$schema": "https://json-schema.org/draft/2020-12/schema", type: "object", properties: { id: { type: "string", format: "uuid", pattern: "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" }, authorId: { type: "string" }, title: { type: "string" }, content: { anyOf: [ { type: "string" }, { type: "null" } ] } }, required: [ "id", "authorId", "title", "content" ], additionalProperties: false}All schema & checks are converted to their closest JSON Schema equivalent.
unrepresentable
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.
z.bigint(); // ❌z.int64(); // ❌z.symbol(); // ❌z.undefined(); // ❌z.void(); // ❌z.date(); // ❌z.map(); // ❌z.set(); // ❌z.transform(); // ❌z.nan(); // ❌z.custom(); // ❌See the unrepresentable section for more information on handling these cases.