Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

json-schema-to-zod

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-schema-to-zod

Converts JSON schema objects or files into Zod schemas

  • 2.4.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Json-Schema-to-Zod

NPM Version NPM Downloads

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

Summary

A runtime package and CLI tool to convert JSON schema (draft 4+) objects or files into Zod schemas in the form of JavaScript code.

Before v2 it used prettier for formatting and json-refs to resolve schemas. To replicate the previous behaviour, please use their respective CLI tools.

Since v2 the CLI supports piped JSON.

Usage

Online

Just paste your JSON schemas here!

CLI

Simplest example
npm i -g json-schema-to-zod
json-schema-to-zod -i mySchema.json -o mySchema.ts
Example with $refs resolved and output formatted
npm i -g json-schema-to-zod json-refs prettier
json-refs resolve mySchema.json | json-schema-to-zod | prettier --parser typescript > mySchema.ts
Options
FlagShorthandFunction
--input-iJSON or a source file path. Required if no data is piped.
--output-oA file path to write to. If not supplied stdout will be used.
--name-nThe name of the schema in the output
--depth-dMaximum depth of recursion in schema before falling back to z.any(). Defaults to 0.
--module-mModule syntax; esm, cjs or none. Defaults to esm in the CLI and none programmaticly.
--type-tExport a named type along with the schema. Requires name to be set and module to be esm.
--noImport-niRemoves the import { z } from 'zod'; or equivalent from the output.

Programmatic

Simple example
import { jsonSchemaToZod } from "json-schema-to-zod";

const myObject = {
  type: "object",
  properties: {
    hello: {
      type: "string",
    },
  },
};

const module = jsonSchemaToZod(myObject, { module: "esm" });

// `type` can be either a string or - outside of the CLI - a boolean. If its `true`, the name of the type will be the name of the schema with a capitalized first letter.
const moduleWithType = jsonSchemaToZod(myObject, { name: "mySchema", module: "esm", type: true });

const cjs = jsonSchemaToZod(myObject, { module: "cjs", name: "mySchema" });

const justTheSchema = jsonSchemaToZod(myObject);
module
import { z } from "zod";

export default z.object({ hello: z.string().optional() });
moduleWithType
import { z } from "zod";

export const mySchema = z.object({ hello: z.string().optional() });
export type MySchema = z.infer<typeof mySchema>;
cjs
const { z } = require("zod");

module.exports = { mySchema: z.object({ hello: z.string().optional() }) };
justTheSchema
z.object({ hello: z.string().optional() });
Example with $refs resolved and output formatted
import { z } from "zod";
import { resolveRefs } from "json-refs";
import { format } from "prettier";
import jsonSchemaToZod from "json-schema-to-zod";

async function example(jsonSchema: Record<string, unknown>): Promise<string>{
  const { resolved } = await resolveRefs(jsonSchema);
  const code = jsonSchemaToZod(resolved);
  const formatted = await format(code, { parser: "typescript" });

  return formatted;
}
Overriding a parser

You can pass a function to the overrideParser option, which represents a function that receives the current schema node and the reference object, and should return a string when it wants to replace a default output. If the default output should be used for the node just return void.

Use at Runtime

The output of this package is not meant to be used at runtime. JSON Schema and Zod does not overlap 100% and the scope of the parsers are purposefully limited in order to help the author avoid a permanent state of chaotic insanity. As this may cause some details of the original schema to be lost in translation, it is instead recommended to use tools such as Ajv to validate your runtime values directly against the original JSON Schema.

That said, it's possible in most cases to use eval. Here's an example that you shouldn't use:

const zodSchema = eval(jsonSchemaToZod({ type: "string" }, { module: "cjs" }));

zodSchema.safeParse("Please just use Ajv instead");

Keywords

FAQs

Package last updated on 05 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc