What is zod-to-json-schema?
The zod-to-json-schema npm package is a utility that converts Zod schemas to JSON Schema. This is useful for generating JSON Schema definitions from Zod validation schemas, which can then be used for various purposes such as API documentation, validation, and more.
What are zod-to-json-schema's main functionalities?
Basic Schema Conversion
This feature allows you to convert a basic Zod schema to a JSON Schema. The example demonstrates converting a Zod object schema with string and integer properties to its JSON Schema equivalent.
const { z } = require('zod');
const { zodToJsonSchema } = require('zod-to-json-schema');
const schema = z.object({
name: z.string(),
age: z.number().int(),
});
const jsonSchema = zodToJsonSchema(schema);
console.log(JSON.stringify(jsonSchema, null, 2));
Nested Schema Conversion
This feature supports the conversion of nested Zod schemas to JSON Schema. The example shows a user schema that includes an address schema, demonstrating how nested objects are handled.
const { z } = require('zod');
const { zodToJsonSchema } = require('zod-to-json-schema');
const addressSchema = z.object({
street: z.string(),
city: z.string(),
});
const userSchema = z.object({
name: z.string(),
address: addressSchema,
});
const jsonSchema = zodToJsonSchema(userSchema);
console.log(JSON.stringify(jsonSchema, null, 2));
Array Schema Conversion
This feature allows for the conversion of Zod schemas that include arrays to JSON Schema. The example demonstrates converting a schema with an array of strings.
const { z } = require('zod');
const { zodToJsonSchema } = require('zod-to-json-schema');
const schema = z.object({
tags: z.array(z.string()),
});
const jsonSchema = zodToJsonSchema(schema);
console.log(JSON.stringify(jsonSchema, null, 2));
Other packages similar to zod-to-json-schema
ajv
AJV (Another JSON Schema Validator) is a popular JSON Schema validator. While it focuses on validating JSON data against JSON Schema, it also provides utilities for generating JSON Schema from various sources. Compared to zod-to-json-schema, AJV is more focused on validation rather than schema conversion.
json-schema-to-typescript
This package converts JSON Schema to TypeScript types. While it operates in the opposite direction of zod-to-json-schema, it serves a similar purpose of bridging the gap between JSON Schema and TypeScript. It is useful for generating TypeScript definitions from existing JSON Schemas.
typescript-json-schema
This package generates JSON Schema from TypeScript types. It is similar to zod-to-json-schema in that it converts type definitions to JSON Schema, but it works directly with TypeScript types instead of Zod schemas.
Zod to Json Schema
Summary
Does what it says on the tin; converts Zod schemas into JSON schemas!
- Supports all relevant schema types, basic string, number and array length validations and string patterns.
- Resolves recursive and recurring schemas with internal
$ref
s. - Also able to target Open API 3 (Swagger) specification for paths.
Usage
import { z } from "zod";
import zodToJsonSchema from "zod-to-json-schema";
const mySchema = z.object({
myString: z.string().min(5),
myUnion: z.union([z.number(), z.boolean()]),
});
const jsonSchema = zodToJsonSchema(mySchema, "mySchema");
Expected output
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/mySchema",
"definitions": {
"mySchema": {
"type": "object",
"properties": {
"myString": {
"type": "string",
"minLength": 5
},
"myUnion": {
"type": ["number", "boolean"]
}
},
"additionalProperties": false,
"required": ["myString", "myUnion"]
}
}
}
Options
Schema name
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).
Options object
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. |
basePath?: string[] | The base path of the root reference builder. Defaults to ["#"]. |
$refStrategy?: "root" | "relative" | "none" | The reference builder strategy; - "root" resolves $refs from the root up, ie: "#/definitions/mySchema".
- "relative" uses relative JSON pointers. See known issues!
- "none" ignores referencing all together, creating a new schema branch even on "seen" schemas. Recursive references defaults to "any", ie
{} . Defaults to "root". |
effectStrategy?: "input" | "any" | The effects output strategy. Defaults to "input". See known issues! |
definitionPath?: "definitions" | "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". |
target?: "jsonSchema7" | "openApi3" | Which spec to target. Defaults to "jsonSchema7" |
Known issues
- When using
.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. - JSON Schemas does not support any other key type than strings for objects. When using
z.record
with any other key type, this will be ignored. - Relative JSON pointers, while published alongside JSON schema draft 2020-12, is not technically a part of it. Currently, most resolvers do not handle them at all.
Versioning
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.
Changelog
https://github.com/StefanTerdell/zod-to-json-schema/blob/master/changelog.md