npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tourradarsam/zod-to-json-schema

v1.0.2

Published

Converts Zod schemas to Json Schemas

Downloads

2

Readme

Zod to Json Schema

NPM Version NPM Downloads

Looking for the exact opposite? Check out json-schema-to-zod

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 $refs.
  • 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()]),
  })
  .describe("My neat object schema");

const jsonSchema = zodToJsonSchema(mySchema, "mySchema");

Expected output

{
  "$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"]
    }
  }
}

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" | "seen" | "none" | The reference builder strategy; "root" resolves $refs from the root up, ie: "#/definitions/mySchema"."relative" uses relative JSON pointers. See known issues!"seen" reuses the output of any "seen" Zod schema. In theory it's a more performant version of "none", but in practice this behaviour can cause issues with nested schemas and has now gotten its own option. "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! | | dateStrategy?: "string" | "integer" | Date strategy, integer allow to specify in unix-time min and max values. Defaults to "string". | | emailStrategy?: "format:email" | "format:idn-email" | "pattern:zod" | Choose how to handle the email string check. Defaults to "format:email". | | definitionPath?: "definitions" | "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". | | target?: "jsonSchema7" | "jsonSchema2019-09" | "openApi3" | 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" | Decide how patterns should be generated, for instance from z.string().includes("@"). By default "escape" is active and non-alphanumeric characters are escaped. This can sometimes cause issues with unicode flagged regex parsers. | | 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". |

Definitions

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:

const myRecurringSchema = z.string();
const myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema });

const myJsonSchema = zodToJsonSchema(myObjectSchema, {
  definitions: { myRecurringSchema },
});

Result

{
  "type": "object",
  "properties": {
    "a": {
      "$ref": "#/definitions/myRecurringSchema"
    },
    "b": {
      "$ref": "#/definitions/myRecurringSchema"
    }
  },
  "definitions": {
    "myRecurringSchema": {
      "type": "string"
    }
  }
}

Error Messages

This feature allows optionally including error messages created via chained function calls for supported zod types:

// 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 });

Result

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "string",
  "format": "email",
  "minLength": 5,
  "errorMessage": {
    "format": "Invalid email",
    "minLength": "Too short"
  }
}

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.

Custom Error Message Support

  • ZodString
    • regex
    • min, max
    • email, cuid, uuid, url
    • endsWith, startsWith
  • ZodNumber
    • min, max, lt, lte, gt, gte,
    • int
    • multipleOf
  • ZodSet
    • min, max
  • ZodArray
    • min, max

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. An exception to this rule is z.enum as is supported since 3.11.3
  • 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.
  • Since v3, the Object parser uses .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.

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