Gathering detailed insights and metrics for zod-to-json-schema
Gathering detailed insights and metrics for zod-to-json-schema
Gathering detailed insights and metrics for zod-to-json-schema
Gathering detailed insights and metrics for zod-to-json-schema
npm install zod-to-json-schema
Typescript
Module System
Node Version
NPM Version
99.4
Supply Chain
99.6
Quality
85.9
Maintenance
100
Vulnerability
100
License
TypeScript (99.8%)
JavaScript (0.2%)
Total Downloads
148,234,547
Last Day
1,338,357
Last Week
5,119,662
Last Month
17,983,272
Last Year
119,661,003
ISC License
1,085 Stars
459 Commits
82 Forks
5 Watchers
6 Branches
25 Contributors
Updated on May 04, 2025
Minified
Minified + Gzipped
Latest Version
3.24.5
Package Id
zod-to-json-schema@3.24.5
Unpacked Size
206.83 kB
Size
43.72 kB
File Count
128
NPM Version
9.2.0
Node Version
18.19.1
Published on
Mar 21, 2025
Cumulative downloads
Total Downloads
Last Day
91.1%
1,338,357
Compared to previous day
Last Week
23.3%
5,119,662
Compared to previous week
Last Month
17.4%
17,983,272
Compared to previous month
Last Year
361%
119,661,003
Compared to previous year
1
Looking for the exact opposite? Check out json-schema-to-zod
Does what it says on the tin; converts Zod schemas into JSON schemas!
$ref
s.A great big thank you to our amazing sponsors! Please consider joining them through my GitHub Sponsors page. Every cent helps, but these fellas have really gone above and beyond 💚:
|
Cut code review time & bugs in half coderabbit.ai |
1import { z } from "zod"; 2import { zodToJsonSchema } from "zod-to-json-schema"; 3 4const mySchema = z 5 .object({ 6 myString: z.string().min(5), 7 myUnion: z.union([z.number(), z.boolean()]), 8 }) 9 .describe("My neat object schema"); 10 11const jsonSchema = zodToJsonSchema(mySchema, "mySchema");
1{ 2 "$schema": "http://json-schema.org/draft-07/schema#", 3 "$ref": "#/definitions/mySchema", 4 "definitions": { 5 "mySchema": { 6 "description": "My neat object schema", 7 "type": "object", 8 "properties": { 9 "myString": { 10 "type": "string", 11 "minLength": 5 12 }, 13 "myUnion": { 14 "type": ["number", "boolean"] 15 } 16 }, 17 "additionalProperties": false, 18 "required": ["myString", "myUnion"] 19 } 20 } 21}
You can pass a string as the second parameter of the main zodToJsonSchema function. If you do, your schema will end up inside a definitions object property on the root and referenced from there. Alternatively, you can pass the name as the name
property of the options object (see below).
Instead of the schema name (or nothing), you can pass an options object as the second parameter. The following options are available:
Option | Effect |
---|---|
name?: string | As described above. |
nameStrategy?: "ref" | "title" | Adds name as "title" meta instead of as a ref as described above |
basePath?: string[] | The base path of the root reference builder. Defaults to ["#"]. |
$refStrategy?: "root" | "relative" | "seen" | "none" | The reference builder strategy;
|
effectStrategy?: "input" | "any" | The effects output strategy. Defaults to "input". See known issues! |
dateStrategy?: "format:date" | "format:date-time" | "string" | "integer" | Date strategy, integer allow to specify in unix-time min and max values. "format:date" creates a string schema with format: "date". "format:date-time" creates a string schema with format: "date-time". "string" is intepreted as "format:date-time". "integer" creates an integer schema with format "unix-time" (unless target "openApi3" is used min max checks are also respected) |
emailStrategy?: "format:email" | "format:idn-email" | "pattern:zod" | Choose how to handle the email string check. Defaults to "format:email". |
base64Strategy?: "format:binary" | "contentEnconding:base64" | "pattern:zod" | Choose how to handle the base64 string check. Defaults to "contentEncoding:base64" as described here. Note that "format:binary" is not represented in the output type as it's not part of the JSON Schema spec and only intended to be used when targeting OpenAPI 3.0. Later versions of OpenAPI support contentEncoding. |
definitionPath?: "definitions" | "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". |
target?: "jsonSchema7" | "jsonSchema2019-09" | "openApi3" | "openAi" | Which spec to target. Defaults to "jsonSchema7" |
strictUnions?: boolean | Scrubs unions of any-like json schemas, like {} or true . Multiple zod types may result in these out of necessity, such as z.instanceof() |
definitions?: Record<string, ZodSchema> | See separate section below |
errorMessages?: boolean | Include custom error messages created via chained function checks for supported zod types. See section below |
markdownDescription?: boolean | Copies the description meta to markdownDescription |
patternStrategy?: "escape" | "preserve" | The Zod string validations .includes() , .startsWith() , and .endsWith() must be converted to regex to be compatible with JSON Schema's pattern . For safety, all non-alphanumeric characters are escape d by default (consider z.string().includes(".") ), but this can occasionally cause problems with Unicode-flagged regex parsers. Use preserve to prevent this escaping behaviour and preserve the exact string written, even if it results in an inaccurate regex. |
applyRegexFlags?: boolean | JSON Schema's pattern doesn't support RegExp flags, but Zod's z.string().regex() does. When this option is true (default false), a best-effort is made to transform regexes into a flag-independent form (e.g. /x/i => /[xX]/ ). Supported flags: i (basic Latin only), m , s . |
pipeStrategy?: "all" | "input" | "output" | Decide which types should be included when using z.pipe , for example z.string().pipe(z.number()) would return both string and number by default, only string for "input" and only number for "output". |
removeAdditionalStrategy?: "passthrough" | "strict" | Decide when additionalProperties should be allowed. See the section on additional properties for details. |
allowedAdditionalProperties?: true | undefined | What value to give additionalProperties when allowed. See the section on additional properties for details. |
rejectedAdditionalProperties?: false | undefined | What value to give additionalProperties when rejected. See the section on additional properties for details. |
override?: callback | See section |
postProcess?: callback | See section |
The definitions option lets you manually add recurring schemas into definitions for cleaner outputs. It's fully compatible with named schemas, changed definitions path and base path. Here's a simple example:
1const myRecurringSchema = z.string(); 2const myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema }); 3 4const myJsonSchema = zodToJsonSchema(myObjectSchema, { 5 definitions: { myRecurringSchema }, 6});
1{ 2 "type": "object", 3 "properties": { 4 "a": { 5 "$ref": "#/definitions/myRecurringSchema" 6 }, 7 "b": { 8 "$ref": "#/definitions/myRecurringSchema" 9 } 10 }, 11 "definitions": { 12 "myRecurringSchema": { 13 "type": "string" 14 } 15 } 16}
This feature allows optionally including error messages created via chained function calls for supported zod types:
1// string schema with additional chained function call checks 2const EmailSchema = z.string().email("Invalid email").min(5, "Too short"); 3 4const jsonSchema = zodToJsonSchema(EmailSchema, { errorMessages: true });
1{ 2 "$schema": "http://json-schema.org/draft-07/schema#", 3 "type": "string", 4 "format": "email", 5 "minLength": 5, 6 "errorMessage": { 7 "format": "Invalid email", 8 "minLength": "Too short" 9 } 10}
This allows for field specific, validation step specific error messages which can be useful for building forms and such. This format is accepted by react-hook-form
's ajv resolver (and therefor ajv-errors
which it uses under the hood). Note that if using AJV with this format will require enabling ajv-errors
as vanilla AJV does not accept this format by default.
By default, Zod removes undeclared properties when parsing object schemas. In order to replicate the expected output of this behaviour, the default for behaviour of zodToJsonSchema is to set "additionalProperties"
to false
(although the correctness of this can be debated). If you wish to allow undeclared properties you can either:
removeAdditionalStrategy
to "strict"
. This will allow additional properties for any object schema that is not declared with .strict()
.removeAdditionalStrategy
set to its default value of "passthrough"
, and add .passtrough()
to your object schema.additionalProperties
keyword using the allowedAdditionalProperties
and/or rejectedAdditionalProperties
options.Some schema definitions (like Googles Gen AI API for instance) does not allow the additionalProperties
keyword at all. Luckily the JSON Schema spec allows for this: leaving the keyword undefined should have the same effect as setting it to true (as per usual YMMV). To enable this behaviour, set the option allowedAdditionalProperties
to undefined
.
To exclude the keyword even when additional properties are not allowed, set the rejectedAdditionalProperties
to undefined
as well.
Heads up ⚠️: Both of these options will be ignored if your schema is declared with .catchall(...)
as the provided schema will be used instead (if valid).
z.object({}) + option | "additionalProperties" value |
---|---|
.strip() (default) | false if strategy is "passtrough" , true if "strict" |
.passtrough() | true |
.strict() | false |
.catchall(z.string()) | { "type": "string" } |
.catchall(z.function()) | undefined (function schemas are not currently parseable) |
Substitute true
and false
for undefined
according to allowedAdditionalProperties
and/or rejectedAdditionalProperties
respectively.
override
This options takes a callback receiving a Zod schema definition, the current reference object (containing the current ref path and other options), an argument containing inforation about wether or not the schema has been encountered before, and a forceResolution argument.
Important: if you don't want to override the current item you have to return the ignoreOverride
symbol exported from the index. This is because undefined
is a valid option to return when you want the property to be excluded from the resulting JSON schema.
1import zodToJsonSchema, { ignoreOverride } from "zod-to-json-schema"; 2 3zodToJsonSchema( 4 z.object({ 5 ignoreThis: z.string(), 6 overrideThis: z.string(), 7 removeThis: z.string(), 8 }), 9 { 10 override: (def, refs) => { 11 const path = refs.currentPath.join("/"); 12 13 if (path === "#/properties/overrideThis") { 14 return { 15 type: "integer", 16 }; 17 } 18 19 if (path === "#/properties/removeThis") { 20 return undefined; 21 } 22 23 // Important! Do not return `undefined` or void unless you want to remove the property from the resulting schema completely. 24 return ignoreOverride; 25 }, 26 }, 27);
Expected output:
1{ 2 "type": "object", 3 "required": ["ignoreThis", "overrideThis"], 4 "properties": { 5 "ignoreThis": { 6 "type": "string" 7 }, 8 "overrideThis": { 9 "type": "integer" 10 } 11 }, 12 "additionalProperties": false 13}
postProcess
Besided receiving all arguments of the override
callback, the postProcess
callback also receives the generated schema. It should always return a JSON Schema, or undefined
if you wish to filter it out. Unlike the override
callback you do not have to return ignoreOverride
if you are happy with the produced schema; simply return it unchanged.
1import zodToJsonSchema, { PostProcessCallback } from "zod-to-json-schema"; 2 3// Define the callback to be used to process the output using the PostProcessCallback type: 4const postProcess: PostProcessCallback = ( 5 // The original output produced by the package itself: 6 jsonSchema, 7 // The ZodSchema def used to produce the original schema: 8 def, 9 // The refs object containing the current path, passed options, etc. 10 refs, 11) => { 12 if (!jsonSchema) { 13 return jsonSchema; 14 } 15 16 // Try to expand description as JSON meta: 17 if (jsonSchema.description) { 18 try { 19 jsonSchema = { 20 ...jsonSchema, 21 ...JSON.parse(jsonSchema.description), 22 }; 23 } catch {} 24 } 25 26 // Make all numbers nullable: 27 if ("type" in jsonSchema! && jsonSchema.type === "number") { 28 jsonSchema.type = ["number", "null"]; 29 } 30 31 // Add the refs path, just because 32 (jsonSchema as any).path = refs.currentPath; 33 34 return jsonSchema; 35}; 36 37const jsonSchema = zodToJsonSchema(zodSchema, { postProcess });
postProcess
for including examples and other metaAdding support for examples and other JSON Schema meta keys are among the most commonly requested features for this project. Unfortunately the current Zod major (3) has pretty anemic support for this, so some userland hacking is required. Since this is such a common usecase I've included a helper function that simply tries to parse any description as JSON and expand it into the resulting schema.
Simply stringify whatever you want added to the output schema as the description, then import and use jsonDescription
as the postProcess option:
1import zodToJsonSchema, { jsonDescription } from "zod-to-json-schema"; 2 3const zodSchema = z.string().describe( 4 JSON.stringify({ 5 title: "My string", 6 description: "My description", 7 examples: ["Foo", "Bar"], 8 whatever: 123, 9 }), 10); 11 12const jsonSchema = zodToJsonSchema(zodSchema, { 13 postProcess: jsonDescription, 14});
Expected output:
1{ 2 "$schema": "http://json-schema.org/draft-07/schema#", 3 "type": "string", 4 "title": "My string", 5 "description": "My description", 6 "examples": ["Foo", "Bar"], 7 "whatever": 123 8}
.transform
, the return type is inferred from the supplied function. In other words, there is no schema for the return type, and there is no way to convert it in runtime. Currently the JSON schema will therefore reflect the input side of the Zod schema and not necessarily the output (the latter aka. z.infer
). If this causes problems with your schema, consider using the effectStrategy "any", which will allow any type of output.z.record
with any other key type, this will be ignored. An exception to this rule is z.enum
as is supported since 3.11.3.isOptional()
to check if a property should be included in required
or not. This has the potentially dangerous behavior of calling .safeParse
with undefined
. To work around this, make sure your preprocess
and other effects callbacks are pure and not liable to throw errors. An issue has been logged in the Zod repo and can be tracked here.$schema
field to: "https://json-schema.org/draft/2020-12/schema#"This package does not follow semantic versioning. The major and minor versions of this package instead reflects feature parity with the Zod package.
I will do my best to keep API-breaking changes to an absolute minimum, but new features may appear as "patches", such as introducing the options pattern in 3.9.1.
https://github.com/StefanTerdell/zod-to-json-schema/blob/master/changelog.md
No vulnerabilities found.
Reason
security policy file detected
Details
Reason
25 commit(s) and 11 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 3/26 approved changesets -- score normalized to 1
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-04-28
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More