2.0.15 • Published 3 months ago

@bpinternal/json-schema-to-zod v2.0.15

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

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. Uses Prettier for formatting.

Usage

Online

Just paste your JSON schemas here!

CLI

Installation:

npm i -g json-schema-to-zod

Example:

json-schema-to-zod -s myJson.json -t mySchema.ts

Options

FlagShorthandFunction
--source-sSource file name (required)
--target-tTarget file name
--name-nThe name of the schema in the output
--deref-dUses json-schema-ref-parser to dereference the schema
--without-defaults-wdIgnore default values in the schema
--recursionDepth-rdMaximum depth of recursion in schema before falling back to z.any(). Defaults to 0. `
--module-mForce module syntax ("esm" or "cjs")

Programmatic

jsonSchemaToZod will output the full module code, including a Zod import. If you only need the Zod schema itself, try one of the parsers directly. If you need to deref your JSON schema, try awaiting jsonSchemaDereffed.

import {
  jsonSchemaToZod,
  jsonSchemaToZodDereffed,
  parseSchema,
} from "json-schema-to-zod";

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

const module = jsonSchemaToZod(myObject);

const dereffed = await jsonSchemaToZodDereffed(myObject);

const schema = parseSchema(myObject);

module/dereffed =

import { z } from "zod";

export default z.object({ hello: z.string().optional() });

schema =

z.object({ hello: z.string().optional() });

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)https://ajv.js.org/ to validate your runtime values directly against the original JSON Schema.

That said, it's possible 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");
2.0.15

3 months ago

2.0.13

4 months ago

2.0.14

4 months ago

1.1.7

6 months ago

1.1.5

6 months ago

1.1.4

6 months ago

1.1.3

6 months ago

1.1.2

6 months ago

1.1.1

6 months ago

1.1.0

11 months ago