### Include Examples and Meta with `jsonDescription` Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Use `jsonDescription` as a `postProcess` callback to parse the Zod schema description as JSON, embedding meta-information like examples and titles into the output schema. This is useful for enriching schemas when Zod's native support is limited. ```typescript import zodToJsonSchema, { jsonDescription } from "zod-to-json-schema"; const zodSchema = z.string().describe( JSON.stringify({ title: "My string", description: "My description", examples: ["Foo", "Bar"], whatever: 123, }), ); const jsonSchema = zodToJsonSchema(zodSchema, { postProcess: jsonDescription, }); ``` -------------------------------- ### Post-processing with jsonDescription Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Use the `postProcess` callback with the `jsonDescription` helper to parse and merge JSON metadata from Zod's `.describe()` strings into the generated JSON Schema. This is useful for adding `title`, `description`, and `examples` not natively supported by Zod. ```typescript import { z } from "zod"; import { zodToJsonSchema, jsonDescription } from "zod-to-json-schema"; const ArticleSchema = z.object({ title: z .string() .min(1) .describe( JSON.stringify({ title: "Article Title", description: "The headline of the article", examples: ["Breaking News", "Feature Story"], }), ), views: z .number() .int() .describe( JSON.stringify({ title: "View Count", examples: [0, 1000, 50000], }), ), }); const jsonSchema = zodToJsonSchema(ArticleSchema, { postProcess: jsonDescription, }); console.log(JSON.stringify(jsonSchema, null, 2)); ``` -------------------------------- ### $refStrategy: 'root' for recursive schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt The default `$refStrategy` is 'root', which generates absolute `$ref` pointers to definitions for recursive schemas. This example shows a recursive `TreeNode` schema. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Recursive schema: a tree node const TreeNode: z.ZodType<{ value: number; children?: any[] }> = z.lazy(() => z.object({ value: z.number(), children: z.array(TreeNode).optional(), }), ); const rootRefSchema = zodToJsonSchema(TreeNode, { name: "TreeNode", $refStrategy: "root", }); console.log(JSON.stringify(rootRefSchema, null, 2)); ``` -------------------------------- ### Using with Zod v3 and v4 Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Demonstrates how to use `zod-to-json-schema` with Zod v3 and v4. Use the `"zod/v3"` import alias when working in a Zod v4 project to pass v3 schemas. ```typescript // In a project with Zod v4 installed, import v3 schemas via alias import { z } from "zod/v3"; import { zodToJsonSchema } from "zod-to-json-schema"; const schema = z.object({ name: z.string(), count: z.number().int().min(0), }); const jsonSchema = zodToJsonSchema(schema); console.log(JSON.stringify(jsonSchema, null, 2)); // { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", ... } // CJS import // const { zodToJsonSchema } = require("zod-to-json-schema"); // Default export also available import zodToJsonSchema2 from "zod-to-json-schema"; const s = zodToJsonSchema2(z.string().min(1)); // { "$schema": "...", "type": "string", "minLength": 1 } ``` -------------------------------- ### target Option - Choosing the Output Specification Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt The `target` option allows you to specify which JSON Schema or OpenAPI specification the output should conform to. This affects how certain Zod types and constraints are translated. ```APIDOC ## target Option ### Description Controls which JSON Schema / OpenAPI specification the output conforms to. Valid values include `"jsonSchema7"` (default), `"jsonSchema2019-09"`, `"openApi3"`, and `"openAi"`. ### Method `zodToJsonSchema(schema: ZodSchema, options: { target: "jsonSchema7" | "jsonSchema2019-09" | "openApi3" | "openAi" }): JsonSchemaObject ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const ProductSchema = z.object({ price: z.number().min(0), currency: z.string().nullable(), tags: z.array(z.string()).optional(), }); // OpenAPI 3.0 target const openApiSchema = zodToJsonSchema(ProductSchema, { target: "openApi3", }); // JSON Schema 2019-09 target const draft2019Schema = zodToJsonSchema(ProductSchema, { target: "jsonSchema2019-09", }); // OpenAI structured output target const openAiSchema = zodToJsonSchema(ProductSchema, { target: "openAi", }); console.log(JSON.stringify(openApiSchema, null, 2)); ``` ### Response #### Success Response (200) - **jsonSchema** (object) - A JSON Schema object conforming to the specified target specification. #### Response Example ```json { "type": "object", "properties": { "price": { "type": "number", "minimum": 0 }, "currency": { "type": "string", "nullable": true }, "tags": { "type": "array", "items": { "type": "string" } } }, "required": ["price", "currency"], "additionalProperties": false } ``` ``` -------------------------------- ### dateStrategy: anyOf for flexible date formats Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Use an array of strategies, like `['format:date-time', 'integer']`, for `dateStrategy` to allow multiple date formats (e.g., date-time strings and Unix timestamps) in the JSON Schema using `anyOf`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const EventSchema = z.object({ startDate: z.date().min(new Date("2024-01-01")), endDate: z.date(), }); // anyOf strategy: accept both date-time strings and integers const flexSchema = zodToJsonSchema(EventSchema, { dateStrategy: ["format:date-time", "integer"], }); console.log(JSON.stringify(flexSchema.properties!["endDate"], null, 2)); ``` -------------------------------- ### Handle z.pipe() with pipeStrategy Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt The `pipeStrategy` option determines which parts of a `z.pipe()` chain are included in the JSON Schema. Use `'all'` (default) for both input and output schemas as `allOf`, `'input'` for only the input schema, or `'output'` for only the output schema. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // A pipe that coerces a string to a number const StringToNumber = z.string().pipe(z.coerce.number().int().positive()); const allSchema = zodToJsonSchema(StringToNumber, { pipeStrategy: "all" }); // { "allOf": [{ "type": "string" }, { "type": "integer", "exclusiveMinimum": 0 }] } ``` ```typescript const inputSchema = zodToJsonSchema(StringToNumber, { pipeStrategy: "input" }); // { "type": "string" } ``` ```typescript const outputSchema = zodToJsonSchema(StringToNumber, { pipeStrategy: "output" }); // { "type": "integer", "exclusiveMinimum": 0 } ``` ```typescript console.log(JSON.stringify(inputSchema, null, 2)); // { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string" } ``` -------------------------------- ### Process Generated Schema with `postProcess` Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md The `postProcess` callback allows modification of the final generated JSON schema. It receives the schema, Zod definition, and references. Use it to add metadata, change types, or filter schemas. ```typescript import zodToJsonSchema, { PostProcessCallback } from "zod-to-json-schema"; // Define the callback to be used to process the output using the PostProcessCallback type: const postProcess: PostProcessCallback = ( // The original output produced by the package itself: jsonSchema, // The ZodSchema def used to produce the original schema: def, // The refs object containing the current path, passed options, etc. refs, ) => { if (!jsonSchema) { return jsonSchema; } // Try to expand description as JSON meta: if (jsonSchema.description) { try { jsonSchema = { ...jsonSchema, ...JSON.parse(jsonSchema.description), }; } catch {} } // Make all numbers nullable: if ("type" in jsonSchema! && jsonSchema.type === "number") { jsonSchema.type = ["number", "null"]; } // Add the refs path, just because (jsonSchema as any).path = refs.currentPath; return jsonSchema; }; const jsonSchema = zodToJsonSchema(zodSchema, { postProcess }); ``` -------------------------------- ### Using `definitions` for Shared Schema Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Manually register schemas into a `definitions` block for reuse via `$ref`. This prevents schemas from being inlined everywhere they appear. Use `definitionPath` to specify the location, e.g., `$defs`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const Address = z.object({ street: z.string(), city: z.string(), zip: z.string().regex(/^\d{5}$/), }); const OrderSchema = z.object({ orderId: z.string().uuid(), billingAddress: Address, shippingAddress: Address, }); const jsonSchema = zodToJsonSchema(OrderSchema, { definitions: { Address }, definitionPath: "$defs", // use $defs instead of definitions }); console.log(JSON.stringify(jsonSchema, null, 2)); ``` -------------------------------- ### zodToJsonSchema - Main Conversion Function Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt The primary export of the library. This function takes a Zod schema and an optional name or options object to return a JSON Schema object. It supports recursive schemas and can place schemas within a `definitions` block when a name is provided. ```APIDOC ## zodToJsonSchema ### Description Converts a Zod schema into a JSON Schema object. It can optionally take a name string to place the schema within a `definitions` block, or an options object for advanced configuration. ### Method `zodToJsonSchema(schema: ZodSchema, nameOrOptions?: string | ZodToJsonSchemaOptions): JsonSchemaObject ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const UserSchema = z.object({ id: z.number().int().positive(), username: z.string().min(3).max(20), email: z.string().email(), role: z.enum(["admin", "user", "guest"]), createdAt: z.date().optional(), }).describe("A registered user"); const jsonSchema = zodToJsonSchema(UserSchema, "User"); console.log(JSON.stringify(jsonSchema, null, 2)); ``` ### Response #### Success Response (200) - **jsonSchema** (object) - A JSON Schema object representing the input Zod schema. #### Response Example ```json { "$schema": "http://json-schema.org/draft-07/schema#", "$ref": "#/definitions/User", "definitions": { "User": { "description": "A registered user", "type": "object", "properties": { "id": { "type": "integer", "minimum": 1 }, "username": { "type": "string", "minLength": 3, "maxLength": 20 }, "email": { "type": "string", "format": "email" }, "role": { "type": "string", "enum": ["admin", "user", "guest"] }, "createdAt": { "type": "string", "format": "date-time" } }, "required": ["id", "username", "email", "role"], "additionalProperties": false } } } ``` ``` -------------------------------- ### Convert Zod Tuple Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Maps Zod tuple schemas to JSON schema arrays. Fixed-length tuples use `minItems` and `maxItems`, while variadic tuples with a rest element use `additionalItems`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Fixed-length tuple const fixedTuple = zodToJsonSchema(z.tuple([z.string(), z.number(), z.boolean()])); // { // "type": "array", // "minItems": 3, // "maxItems": 3, // "items": [{ "type": "string" }, { "type": "number" }, { "type": "boolean" }] // } ``` ```typescript // Variadic tuple with rest const variadicTuple = zodToJsonSchema( z.tuple([z.string(), z.number()]).rest(z.boolean()), ); // { // "type": "array", // "minItems": 2, // "items": [{ "type": "string" }, { "type": "number" }], // "additionalItems": { "type": "boolean" } // } ``` -------------------------------- ### Convert Zod Record, Map, and Set Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Maps Zod record, map, and set schemas to JSON schema objects. `z.record` uses `additionalProperties`, `z.map` can be a tuple-array or record, and `z.set` uses `uniqueItems`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Record with constrained keys const recordSchema = zodToJsonSchema( z.record(z.string().min(1).max(50), z.number().int()), ); // { // "type": "object", // "additionalProperties": { "type": "integer" }, // "propertyNames": { "minLength": 1, "maxLength": 50 } // } ``` ```typescript // Map as tuple-array (default) const mapSchema = zodToJsonSchema(z.map(z.string(), z.boolean())); // { // "type": "array", "maxItems": 125, // "items": { "type": "array", "items": [{ "type": "string" }, { "type": "boolean" }], "minItems": 2, "maxItems": 2 } // } ``` ```typescript // Map as record const mapAsRecord = zodToJsonSchema(z.map(z.string(), z.number()), { mapStrategy: "record", }); // { "type": "object", "additionalProperties": { "type": "number" } } ``` ```typescript // Set → uniqueItems array const setSchema = zodToJsonSchema(z.set(z.string()).min(1).max(5)); // { "type": "array", "uniqueItems": true, "items": { "type": "string" }, "minItems": 1, "maxItems": 5 } ``` -------------------------------- ### Nullable, Optional, and Default Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Demonstrates how zod-to-json-schema handles nullable, optional, and default fields. `z.optional` omits fields from `required`. `z.nullable` adds `null` to the type. `z.default` does not embed the default value in the JSON Schema. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const schema = zodToJsonSchema( z.object({ required: z.string(), optional: z.string().optional(), // omitted from required[] nullable: z.string().nullable(), // type: ["string", "null"] withDefault: z.string().default("hello"), // type: "string" (default not emitted) complexNull: z.object({ x: z.number() }).nullable(), // anyOf: [{...}, {type:"null"}] }), ); // "required": ["required", "nullable", "withDefault", "complexNull"] // nullable → { "type": ["string", "null"] } // complexNull → { "anyOf": [{ "type": "object", ... }, { "type": "null" }] } ``` -------------------------------- ### Transform and Refine Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Shows how `z.transform` and `z.refine` schemas are handled by `zod-to-json-schema`. The `effectStrategy` option controls output: `'input'` (default) reflects the input schema, while `'any'` allows any type. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const CoerceToDate = z.string().transform((s) => new Date(s)); // Default: reflects input side (string) const inputSchema = zodToJsonSchema(CoerceToDate); // { "$schema": "...", "type": "string" } // "any": allows any type (empty schema {}) const anySchema = zodToJsonSchema(CoerceToDate, { effectStrategy: "any" }); // { "$schema": "..." } // z.refine — treated the same way (reflects input type) const PositiveInt = z.number().int().refine((n) => n > 0, "Must be positive"); const refineSchema = zodToJsonSchema(PositiveInt); // { "$schema": "...", "type": "integer" } ``` -------------------------------- ### Configure Additional Properties Handling Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Control how undeclared properties are handled in object schemas using 'removeAdditionalStrategy'. Options include 'strict' and 'passthrough'. ```typescript const myObjectSchema = z.object({ a: z.string() }); // Example with default 'passthrough' strategy const schemaPassthrough = zodToJsonSchema(myObjectSchema, { removeAdditionalStrategy: "passthrough", }); // Example with 'strict' strategy const schemaStrict = zodToJsonSchema(myObjectSchema.strict(), { removeAdditionalStrategy: "strict", }); ``` -------------------------------- ### Convert Zod Union, Intersection, and Discriminated Union Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Handles primitive unions, literal unions, mixed unions, intersections, and discriminated unions. Mixed unions and discriminated unions map to `anyOf`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Primitive union → collapsed type array const primitiveUnion = zodToJsonSchema(z.union([z.string(), z.number(), z.null()])); // { "type": ["string", "number", "null"] } ``` ```typescript // Literal union → enum const literalUnion = zodToJsonSchema(z.union([z.literal("a"), z.literal("b"), z.literal("c")])); // { "type": "string", "enum": ["a", "b", "c"] } ``` ```typescript // Mixed union → anyOf const mixedUnion = zodToJsonSchema( z.union([z.string().email(), z.object({ id: z.number() })]), ); // { "anyOf": [{ "type": "string", "format": "email" }, { "type": "object", ... }] } ``` ```typescript // Intersection → allOf const intersection = zodToJsonSchema( z.intersection( z.object({ name: z.string() }), z.object({ age: z.number().int() }), ), ); // { "allOf": [{ "type": "object", "properties": { "name": ... } }, { ... "age": ... }] } ``` ```typescript // Discriminated union const DiscriminatedSchema = z.discriminatedUnion("kind", [ z.object({ kind: z.literal("circle"), radius: z.number() }), z.object({ kind: z.literal("square"), side: z.number() }), ]); const discSchema = zodToJsonSchema(DiscriminatedSchema); // { "anyOf": [ { ...circle... }, { ...square... } ] } ``` -------------------------------- ### Using `override` for Custom Schema Transformations Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt A callback invoked for every Zod schema node before normal parsing. Return a custom JSON Schema object to override the default output, `undefined` to omit the property, or `ignoreOverride` to let normal parsing proceed. This allows for custom per-schema transformations. ```typescript import { z } from "zod"; import { zodToJsonSchema, ignoreOverride } from "zod-to-json-schema"; const FormSchema = z.object({ publicField: z.string(), secretToken: z.string(), legacyId: z.number(), }); const jsonSchema = zodToJsonSchema(FormSchema, { override: (def, refs) => { const path = refs.currentPath.join("/"); // Remove the secretToken field from the output schema if (path === "#/properties/secretToken") { return undefined; } // Override legacyId to be treated as a string if (path === "#/properties/legacyId") { return { type: "string", pattern: "^[0-9]+$" }; } return ignoreOverride; }, }); console.log(JSON.stringify(jsonSchema, null, 2)); ``` -------------------------------- ### Control additionalProperties with removeAdditionalStrategy Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Use `removeAdditionalStrategy: "strict"` to control `additionalProperties` based on whether the Zod object uses `.strict()`. Setting `allowedAdditionalProperties` or `rejectedAdditionalProperties` to `undefined` omits the keyword entirely, which is required by some APIs like Google Gemini. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const FlexSchema = z.object({ name: z.string() }); // .strip() by default const StrictSchema = z.object({ name: z.string() }).strict(); const PassthroughSchema = z.object({ name: z.string() }).passthrough(); // Strategy "strict": only .strict() objects get additionalProperties: false const result = zodToJsonSchema( z.object({ flex: FlexSchema, strict: StrictSchema, passthrough: PassthroughSchema }), { removeAdditionalStrategy: "strict" }, ); // flex.additionalProperties → true (allowed) // strict.additionalProperties → false (rejected) // passthrough.additionalProperties → true (allowed) ``` ```typescript // Omit the keyword entirely (for Google Gemini / similar APIs) const noKeywordSchema = zodToJsonSchema(FlexSchema, { allowedAdditionalProperties: undefined, rejectedAdditionalProperties: undefined, }); console.log("additionalProperties" in noKeywordSchema); // false ``` -------------------------------- ### Specify Target JSON Schema Specification Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Control the output JSON Schema specification using the `target` option. Supported values include `jsonSchema7` (default), `jsonSchema2019-09`, `openApi3`, and `openAi`. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const ProductSchema = z.object({ price: z.number().min(0), currency: z.string().nullable(), tags: z.array(z.string()).optional(), }); // OpenAPI 3.0 target — nullable becomes { type, nullable: true } const openApiSchema = zodToJsonSchema(ProductSchema, { target: "openApi3", }); // JSON Schema 2019-09 target — intersections gain unevaluatedProperties const draft2019Schema = zodToJsonSchema(ProductSchema, { target: "jsonSchema2019-09", }); // OpenAI structured output target — optional props become required+nullable const openAiSchema = zodToJsonSchema(ProductSchema, { target: "openAi", }); console.log(JSON.stringify(openApiSchema, null, 2)); ``` -------------------------------- ### Disallow Additional Properties Keyword Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Use 'allowedAdditionalProperties' and 'rejectedAdditionalProperties' to control the presence of the 'additionalProperties' keyword in the generated schema. Set to undefined to omit the keyword. ```typescript const myObjectSchema = z.object({ a: z.string() }); // To disallow additional properties entirely (omit keyword) const schemaNoAdditional = zodToJsonSchema(myObjectSchema, { allowedAdditionalProperties: undefined, }); // To explicitly reject additional properties (omit keyword) const schemaRejectedAdditional = zodToJsonSchema(myObjectSchema, { rejectedAdditionalProperties: undefined, }); // To allow additional properties (omit keyword) const schemaAllowedAdditional = zodToJsonSchema(myObjectSchema, { allowedAdditionalProperties: undefined, }); ``` -------------------------------- ### Basic Zod to JSON Schema Conversion Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Use this snippet to convert a Zod object schema into its JSON schema representation. Ensure Zod is imported, and the schema is passed to the zodToJsonSchema function. ```typescript import { z } from "zod"; // Or, using v3.25 or v4, "zod/v3" import { zodToJsonSchema } from "zod-to-json-schema"; const mySchema = z .object({ myString: z.string().min(5), myUnion: z.union([z.number(), z.boolean()]), }) .describe("My neat object schema"); const jsonSchema = zodToJsonSchema(mySchema, "mySchema"); ``` ```json { "$schema": "http://json-schema.org/draft-07/schema#", "$ref": "#/definitions/mySchema", "definitions": { "mySchema": { "description": "My neat object schema", "type": "object", "properties": { "myString": { "type": "string", "minLength": 5 }, "myUnion": { "type": ["number", "boolean"] } }, "additionalProperties": false, "required": ["myString", "myUnion"] } } } ``` -------------------------------- ### Map Zod string validations to JSON Schema Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt This snippet demonstrates how various Zod string checks are mapped to standard JSON Schema keywords or regex patterns. The `applyRegexFlags` option is used here to adjust regex mapping. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const schema = zodToJsonSchema( z.object({ email: z.string().email(), url: z.string().url(), uuid: z.string().uuid(), ip: z.string().ip(), datetime: z.string().datetime(), date: z.string().date(), duration: z.string().duration(), base64: z.string().base64(), jwt: z.string().jwt(), nanoid: z.string().nanoid(), pattern: z.string().regex(/^[A-Z]{3}-\d{4}$/i), starts: z.string().startsWith("SKU-"), ends: z.string().endsWith(".pdf"), includes: z.string().includes("keyword"), bounded: z.string().min(5).max(100), }), { applyRegexFlags: true }, ); // email → { type: "string", format: "email" } // url → { type: "string", format: "uri" } // uuid → { type: "string", format: "uuid" } // ip → anyOf: [{ format: "ipv4" }, { format: "ipv6" }] // datetime → { type: "string", format: "date-time" } // base64 → { type: "string", contentEncoding: "base64" } // jwt → { type: "string", pattern: "^[A-Za-z0-9-_]+\\...." } // pattern → { type: "string", pattern: "^[a-zA-Z]{3}-[0-9]{4}$" } // starts → { type: "string", pattern: "^SKU\\-" } // bounded → { type: "string", minLength: 5, maxLength: 100 } ``` -------------------------------- ### Define Recurring Schemas with Definitions Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Use the 'definitions' option to include recurring schemas in the output for cleaner JSON schemas. This is compatible with named schemas and custom definition paths. ```typescript const myRecurringSchema = z.string(); const myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema }); const myJsonSchema = zodToJsonSchema(myObjectSchema, { definitions: { myRecurringSchema }, }); ``` ```json { "type": "object", "properties": { "a": { "$ref": "#/definitions/myRecurringSchema" }, "b": { "$ref": "#/definitions/myRecurringSchema" } }, "definitions": { "myRecurringSchema": { "type": "string" } } } ``` -------------------------------- ### Override Schema Properties with `override` Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Use the `override` callback to modify or remove schema properties. Return `undefined` to exclude a property, or `ignoreOverride` to keep the default behavior. This is useful for changing types or removing unwanted fields. ```typescript import zodToJsonSchema, { ignoreOverride } from "zod-to-json-schema"; zodToJsonSchema( z.object({ ignoreThis: z.string(), overrideThis: z.string(), removeThis: z.string(), }), { override: (def, refs) => { const path = refs.currentPath.join("/"); if (path === "#/properties/overrideThis") { return { type: "integer", }; } if (path === "#/properties/removeThis") { return undefined; } // Important! Do not return `undefined` or void unless you want to remove the property from the resulting schema completely. return ignoreOverride; }, }, ); ``` -------------------------------- ### dateStrategy: 'integer' for Unix timestamps Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Configure `dateStrategy` to 'integer' to serialize `z.date()` fields as Unix timestamps. This is one of several options for controlling date output format. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const EventSchema = z.object({ startDate: z.date().min(new Date("2024-01-01")), endDate: z.date(), }); // Integer (Unix time) strategy const intSchema = zodToJsonSchema(EventSchema, { dateStrategy: "integer", }); console.log(JSON.stringify(intSchema.properties!["startDate"], null, 2)); ``` -------------------------------- ### Convert Zod Schema to JSON Schema Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Use the `zodToJsonSchema` function to convert a Zod schema into a JSON Schema object. Provide a name to place the schema in a `definitions` block with a root `$ref`. ```typescript import { z } from "zod"; // or "zod/v3" import { zodToJsonSchema } from "zod-to-json-schema"; const UserSchema = z .object({ id: z.number().int().positive(), username: z.string().min(3).max(20), email: z.string().email(), role: z.enum(["admin", "user", "guest"]), createdAt: z.date().optional(), }) .describe("A registered user"); const jsonSchema = zodToJsonSchema(UserSchema, "User"); console.log(JSON.stringify(jsonSchema, null, 2)); ``` -------------------------------- ### nameStrategy: 'title' for schema naming Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Set `nameStrategy` to 'title' to embed the schema name directly as a `title` field on the root schema, instead of using a `$ref` in the `definitions` block. This is useful when you don't need reusable definitions. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const TagSchema = z.object({ id: z.number(), label: z.string() }); // nameStrategy: "title" — no $ref, name embedded as title const schema = zodToJsonSchema(TagSchema, { name: "Tag", nameStrategy: "title", }); console.log(JSON.stringify(schema, null, 2)); ``` -------------------------------- ### Convert Zod Enum and Native Enum Schemas Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt Converts Zod enums to JSON schema with `type: "string"` and `enum` array. Native enums handle TypeScript enums, mapping numeric and string values appropriately. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; // Zod enum const Direction = z.enum(["North", "South", "East", "West"]); const dirSchema = zodToJsonSchema(Direction); // { "$schema": "...", "type": "string", "enum": ["North", "South", "East", "West"] } ``` ```typescript // TypeScript native enum enum Status { Active = "active", Inactive = "inactive", Pending = "pending", } const statusSchema = zodToJsonSchema(z.nativeEnum(Status)); // { "$schema": "...", "type": "string", "enum": ["active", "inactive", "pending"] } ``` ```typescript // Union of enums is merged into a single enum const Combined = z.union([ z.enum(["red", "green"]), z.enum(["blue", "yellow"]), ]); const combinedSchema = zodToJsonSchema(Combined); // { "type": "string", "enum": ["red", "green", "blue", "yellow"] } ``` -------------------------------- ### Include Error Messages in JSON Schema Source: https://github.com/stefanterdell/zod-to-json-schema/blob/master/README.md Enable the 'errorMessages' option to include error messages from chained Zod function calls. This format is compatible with react-hook-form's ajv resolver. ```typescript // string schema with additional chained function call checks const EmailSchema = z.string().email("Invalid email").min(5, "Too short"); const jsonSchema = zodToJsonSchema(EmailSchema, { errorMessages: true }); ``` ```json { "$schema": "http://json-schema.org/draft-07/schema#", "type": "string", "format": "email", "minLength": 5, "errorMessage": { "format": "Invalid email", "minLength": "Too short" } } ``` -------------------------------- ### Using `errorMessages` for Validation Errors Source: https://context7.com/stefanterdell/zod-to-json-schema/llms.txt When `true`, custom error messages chained onto Zod validators are embedded in the JSON Schema output under `errorMessage` keys. This is compatible with `ajv-errors` for per-field validation error messages. ```typescript import { z } from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; const RegistrationSchema = z.object({ username: z .string() .min(3, "Username must be at least 3 characters") .max(20, "Username must be at most 20 characters"), email: z.string().email("Please provide a valid email address"), age: z .number() .int("Age must be a whole number") .min(18, "Must be 18 or older"), }); const jsonSchema = zodToJsonSchema(RegistrationSchema, { errorMessages: true, }); console.log(JSON.stringify(jsonSchema, null, 2)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.