CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-n8n--json-schema-to-zod

Converts JSON schema objects into Zod schemas at runtime

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

JSON Schema to Zod

A TypeScript library that converts JSON Schema objects (draft 4+) into Zod schemas at runtime. It provides comprehensive support for all JSON Schema features including objects, arrays, strings, numbers, unions, conditionals, and complex validation constraints.

Package Information

  • Package Name: @n8n/json-schema-to-zod
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @n8n/json-schema-to-zod

Core Imports

import { jsonSchemaToZod } from "@n8n/json-schema-to-zod";
import type { JsonSchema, JsonSchemaToZodOptions } from "@n8n/json-schema-to-zod";

For CommonJS:

const { jsonSchemaToZod } = require("@n8n/json-schema-to-zod");

Basic Usage

import { jsonSchemaToZod } from "@n8n/json-schema-to-zod";
import { z } from "zod";

// Simple string schema
const jsonSchema = {
  type: "string",
  minLength: 3,
  maxLength: 50
};

const zodSchema = jsonSchemaToZod(jsonSchema);
// Result: z.string().min(3).max(50)

// Complex object schema
const objectSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number", minimum: 0 },
    email: { type: "string", format: "email" }
  },
  required: ["name", "age"]
};

const zodObjectSchema = jsonSchemaToZod(objectSchema);
// Result: z.object({ name: z.string(), age: z.number().min(0), email: z.string().email().optional() })

// With options
const zodSchemaWithOptions = jsonSchemaToZod(jsonSchema, {
  withoutDefaults: true,
  withoutDescribes: true
});

Capabilities

Schema Conversion

Converts JSON Schema objects into equivalent Zod schemas with full type safety.

/**
 * Converts a JSON schema object to a Zod schema
 * @param schema - JSON schema object or boolean to convert
 * @param options - Optional configuration for the conversion
 * @returns Zod schema equivalent to the input JSON schema
 */
function jsonSchemaToZod<T extends z.ZodTypeAny = z.ZodTypeAny>(
  schema: JsonSchema,
  options?: JsonSchemaToZodOptions
): T;

Usage Example:

import { jsonSchemaToZod } from "@n8n/json-schema-to-zod";
import { z } from "zod";

// Array schema with validation
const arraySchema = {
  type: "array",
  items: { type: "string" },
  minItems: 1,
  maxItems: 10
};

const zodArray = jsonSchemaToZod<z.ZodArray<z.ZodString>>(arraySchema);
// Result: z.array(z.string()).min(1).max(10)

// Union schema (anyOf)
const unionSchema = {
  anyOf: [
    { type: "string" },
    { type: "number" }
  ]
};

const zodUnion = jsonSchemaToZod(unionSchema);
// Result: z.union([z.string(), z.number()])

Parser Override System

Allows custom parsing behavior for specific schema patterns through the parser override function.

/**
 * Parser override function type for custom schema parsing
 * @param schema - The JSON schema object being parsed
 * @param refs - Reference tracking and options context
 * @returns Custom Zod schema or undefined to use default parsing
 */
type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny | undefined;

Usage Example:

import { jsonSchemaToZod } from "@n8n/json-schema-to-zod";
import { z } from "zod";

const customParser = (schema, refs) => {
  // Custom handling for string schemas with specific format
  if (schema.type === "string" && schema.format === "uuid") {
    return z.string().uuid();
  }
  // Return undefined to use default parsing
  return undefined;
};

const schema = {
  type: "string",
  format: "uuid"
};

const zodSchema = jsonSchemaToZod(schema, {
  parserOverride: customParser
});
// Result: z.string().uuid()

Types

Core Types

/**
 * Represents any serializable value
 */
type Serializable = 
  | { [key: string]: Serializable }
  | Serializable[]
  | string
  | number
  | boolean
  | null;

/**
 * Main JSON schema type - can be an object or boolean
 */
type JsonSchema = JsonSchemaObject | boolean;

/**
 * JSON Schema object with all standard properties
 */
interface JsonSchemaObject {
  // Type definition
  type?: string | string[];

  // Object properties
  properties?: { [key: string]: JsonSchema };
  additionalProperties?: JsonSchema;
  unevaluatedProperties?: JsonSchema;
  patternProperties?: { [key: string]: JsonSchema };
  minProperties?: number;
  maxProperties?: number;
  required?: string[] | boolean;
  propertyNames?: JsonSchema;

  // Array properties
  items?: JsonSchema | JsonSchema[];
  additionalItems?: JsonSchema;
  minItems?: number;
  maxItems?: number;
  uniqueItems?: boolean;

  // String properties
  minLength?: number;
  maxLength?: number;
  pattern?: string;
  format?: string;

  // Number properties
  minimum?: number;
  maximum?: number;
  exclusiveMinimum?: number | boolean;
  exclusiveMaximum?: number | boolean;
  multipleOf?: number;

  // Union/combination properties
  anyOf?: JsonSchema[];
  allOf?: JsonSchema[];
  oneOf?: JsonSchema[];

  // Conditional properties
  if?: JsonSchema;
  then?: JsonSchema;
  else?: JsonSchema;

  // Shared properties
  const?: Serializable;
  enum?: Serializable[];
  errorMessage?: { [key: string]: string | undefined };
  description?: string;
  default?: Serializable;
  readOnly?: boolean;
  not?: JsonSchema;
  contentEncoding?: string;
  nullable?: boolean;
}

Configuration Types

/**
 * Options for customizing the JSON schema to Zod conversion
 */
interface JsonSchemaToZodOptions {
  /** Exclude default values from the generated Zod schema */
  withoutDefaults?: boolean;
  /** Exclude descriptions from the generated Zod schema */
  withoutDescribes?: boolean;
  /** Custom parser function for overriding default parsing behavior */
  parserOverride?: ParserOverride;
  /** Maximum parsing depth to prevent infinite recursion */
  depth?: number;
}

/**
 * Internal reference tracking type used during parsing
 */
interface Refs extends JsonSchemaToZodOptions {
  /** Current parsing path for error reporting and debugging */
  path: Array<string | number>;
  /** Map for tracking seen objects to handle circular references */
  seen: Map<object | boolean, { n: number; r: z.ZodTypeAny | undefined }>;
}

Parser Function Types

/**
 * Parser selector function type for choosing appropriate parser
 */
type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny;

/**
 * Parser override function type for custom schema parsing
 */
type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny | undefined;

Supported JSON Schema Features

The library provides comprehensive support for JSON Schema draft 4+ features:

  • Primitive Types: string, number, integer, boolean, null
  • Object Schemas: properties, required fields, additional properties, pattern properties
  • Array Schemas: items, additional items, length constraints, uniqueness
  • String Validation: length constraints, patterns, format validation
  • Number Validation: min/max values, exclusive bounds, multiple constraints
  • Union Types: anyOf, oneOf, allOf combinations
  • Conditional Logic: if/then/else schemas
  • Constants: const and enum values
  • Descriptions: schema documentation preservation
  • Default Values: automatic default value application
  • Nullable Types: nullable schema support
  • Circular References: automatic detection and handling
  • Error Messages: custom error message support
  • Read-only: read-only property support

Error Handling

The library handles various edge cases and validation scenarios:

  • Circular References: Automatically detected and resolved using reference tracking
  • Invalid Schemas: Graceful handling of malformed JSON schema objects
  • Type Mismatches: Proper error reporting for incompatible schema definitions
  • Deep Nesting: Depth control to prevent stack overflow on deeply nested schemas
  • Missing Dependencies: Clear error messages when required Zod peer dependency is missing
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@n8n/json-schema-to-zod@1.5.x
Publish Source
CLI
Badge
tessl/npm-n8n--json-schema-to-zod badge