### Install JSON Schema to Zod with pnpm Source: https://github.com/dmitryrechkin/json-schema-to-zod/blob/main/README.md Install the package using pnpm. Ensure your project is set up for TypeScript and ES modules. ```bash pnpm add @dmitryrechkin/json-schema-to-zod ``` -------------------------------- ### Convert Primitive JSON Schema Types to Zod Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Demonstrates conversion of basic JSON Schema types like `string`, `number`, `integer`, and `boolean` to their corresponding Zod types. Includes examples of numeric constraints (`minimum`, `maximum`, `exclusiveMaximum`) and the `integer` constraint. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // string const strSchema = JSONSchemaToZod.convert({ type: 'string' }); strSchema.parse('hello'); // ✓ // number with bounds const numSchema = JSONSchemaToZod.convert({ type: 'number', minimum: 0, maximum: 100, exclusiveMaximum: true, }); numSchema.parse(50); // ✓ numSchema.parse(100); // ✗ — must be < 100 // integer constraint const intSchema = JSONSchemaToZod.convert({ type: 'integer' }); intSchema.parse(5); // ✓ intSchema.parse(5.5); // ✗ — must be an integer // boolean const boolSchema = JSONSchemaToZod.convert({ type: 'boolean' }); boolSchema.parse(true); // ✓ boolSchema.parse('yes'); // ✗ ``` -------------------------------- ### Run Unit Tests with pnpm Source: https://github.com/dmitryrechkin/json-schema-to-zod/blob/main/README.md Execute the project's unit tests using pnpm. Ensure code passes linting and tests before contributing. ```bash pnpm test ``` -------------------------------- ### String Constraints Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Covers the application of `minLength`, `maxLength`, `pattern`, and `enum` constraints to string schemas. ```APIDOC ## String Constraints (`minLength`, `maxLength`, `pattern`, `enum`) ### Description Applies length constraints (`minLength`, `maxLength`), regular expression patterns (`pattern`), and enumerated values (`enum`) to string schemas. ### Method `JSONSchemaToZod.convert(schema: JSONSchema): ZodSchema` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - A JSON Schema object with `type: 'string'` and one or more of the following keywords: `minLength`, `maxLength`, `pattern`, `enum`. ### Request Example ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Pattern constraint const phoneSchema = JSONSchemaToZod.convert({ type: 'string', pattern: '^\\+?[1-9]\\d{1,14}$', }); phoneSchema.parse('+1234567890'); // ✓ phoneSchema.parse('abc'); // ✗ — does not match pattern // Enum constraint const colorSchema = JSONSchemaToZod.convert({ type: 'string', enum: ['red', 'green', 'blue'], }); colorSchema.parse('red'); // ✓ colorSchema.parse('yellow'); // ✗ — not in enum // Length constraints const usernameSchema = JSONSchemaToZod.convert({ type: 'string', minLength: 3, maxLength: 20, }); usernameSchema.parse('alice'); // ✓ ``` ### Response #### Success Response (ZodSchema) - Returns a Zod string schema with the specified length, pattern, and/or enum constraints applied. #### Response Example ```typescript // ZodString with .min(3).max(20) // ZodString with .regex(/^\+?[1-9]\d{1,14}$/) // ZodString with .enum(['red', 'green', 'blue']) ``` ``` -------------------------------- ### Primitive Type Conversion Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Demonstrates the conversion of basic JSON Schema primitive types to their corresponding Zod types. ```APIDOC ## Primitive Type Conversion ### Description Converts JSON Schema primitive types like `string`, `number`, `integer`, and `boolean` into their Zod equivalents, applying any specified constraints. ### Method `JSONSchemaToZod.convert(schema: JSONSchema): ZodSchema` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - A JSON Schema object defining a primitive type. ### Request Example ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // String schema const strSchema = JSONSchemaToZod.convert({ type: 'string' }); strSchema.parse('hello'); // ✓ // Number schema with bounds const numSchema = JSONSchemaToZod.convert({ type: 'number', minimum: 0, maximum: 100, exclusiveMaximum: true, }); numSchema.parse(50); // ✓ numSchema.parse(100); // ✗ — must be < 100 // Integer constraint const intSchema = JSONSchemaToZod.convert({ type: 'integer' }); intSchema.parse(5); // ✓ intSchema.parse(5.5); // ✗ — must be an integer // Boolean schema const boolSchema = JSONSchemaToZod.convert({ type: 'boolean' }); boolSchema.parse(true); // ✓ boolSchema.parse('yes'); // ✗ ``` ### Response #### Success Response (ZodSchema) - Returns a Zod schema object representing the primitive type with applied constraints. #### Response Example ```typescript // For type: 'string' -> ZodString // For type: 'number' with constraints -> ZodNumber with specific refinements // For type: 'integer' -> ZodNumber with refinement for integer // For type: 'boolean' -> ZodBoolean ``` ``` -------------------------------- ### Array Schema Conversion with Item Types and Constraints Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Converts `array` type schemas, including typed item schemas and array-level constraints like `minItems`, `maxItems`, and `uniqueItems`. Ensure array items match the specified type and uniqueness constraints. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Typed array const tagsSchema = JSONSchemaToZod.convert({ type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 5, }); tagsSchema.parse(['typescript', 'zod']); // ✓ tagsSchema.parse([]); // ✗ — minItems: 1 tagsSchema.parse([1, 2]); // ✗ — items must be strings // Unique items constraint const setSchema = JSONSchemaToZod.convert({ type: 'array', items: { type: 'number' }, uniqueItems: true, }); setSchema.parse([1, 2, 3]); // ✓ setSchema.parse([1, 2, 2]); // ✗ — duplicate items ``` -------------------------------- ### Basic JSON Schema to Zod Conversion Source: https://github.com/dmitryrechkin/json-schema-to-zod/blob/main/README.md Convert a simple JSON schema object into a Zod schema for basic data validation. Requires importing JSONSchemaToZod. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; const jsonSchema = { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number', minimum: 0 }, }, required: ['name', 'age'], }; const zodSchema = JSONSchemaToZod.convert(jsonSchema); // Now you can use `zodSchema` to validate data const parsedData = zodSchema.parse({ name: 'John Doe', age: 30, }); console.log(parsedData); // Output: { name: 'John Doe', age: 30 } ``` -------------------------------- ### String Format Validation Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Explains how string formats like 'email', 'uri', 'uuid', 'date', and 'date-time' are converted into Zod format validators. ```APIDOC ## String Format Validation ### Description Applies Zod's built-in format validators to string schemas based on the `format` keyword in the JSON Schema. Supported formats include `email`, `date-time`, `uri`, `uuid`, and `date`. ### Method `JSONSchemaToZod.convert(schema: JSONSchema): ZodSchema` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - A JSON Schema object with `type: 'string'` and a `format` keyword. ### Request Example ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Email format const emailSchema = JSONSchemaToZod.convert({ type: 'string', format: 'email' }); emailSchema.parse('user@example.com'); // ✓ emailSchema.parse('not-an-email'); // ✗ // UUID format const uuidSchema = JSONSchemaToZod.convert({ type: 'string', format: 'uuid' }); uuidSchema.parse('550e8400-e29b-41d4-a716-446655440000'); // ✓ // URI format const urlSchema = JSONSchemaToZod.convert({ type: 'string', format: 'uri' }); urlSchema.parse('https://example.com'); // ✓ // Date format const dateSchema = JSONSchemaToZod.convert({ type: 'string', format: 'date' }); dateSchema.parse('2024-01-15'); // ✓ // Date-time format const datetimeSchema = JSONSchemaToZod.convert({ type: 'string', format: 'date-time' }); datetimeSchema.parse('2024-01-15T10:30:00Z'); // ✓ ``` ### Response #### Success Response (ZodSchema) - Returns a Zod string schema with the appropriate format validator applied. #### Response Example ```typescript // ZodString with .email() refinement // ZodString with .uuid() refinement // ZodString with .url() refinement // ZodString with .date() refinement // ZodString with .datetime() refinement ``` ``` -------------------------------- ### Nullable Types: Type Array and anyOf with null Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Supports two JSON Schema patterns for nullable fields: the `type` array syntax and the `anyOf` with `{ type: 'null' }` syntax. Both result in a Zod schema that accepts the specified type or null. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Type array syntax const nullableStr = JSONSchemaToZod.convert({ type: ['string', 'null'] }); nullableStr.parse('hello'); // ✓ nullableStr.parse(null); // ✓ nullableStr.parse(123); // ✗ // anyOf syntax (equivalent result) const anyOfNullable = JSONSchemaToZod.convert({ anyOf: [{ type: 'string', format: 'email' }, { type: 'null' }], }); anyOfNullable.parse('user@example.com'); // ✓ anyOfNullable.parse(null); // ✓ anyOfNullable.parse('not-an-email'); // ✗ // Nullable field inside an object const profileSchema = JSONSchemaToZod.convert({ type: 'object', properties: { username: { type: 'string' }, bio: { type: ['string', 'null'] }, }, required: ['username'], }); profileSchema.parse({ username: 'alice', bio: null }); // ✓ profileSchema.parse({ username: 'alice', bio: 'Hello' }); // ✓ profileSchema.parse({ username: 'alice' }); // ✓ — bio is optional ``` -------------------------------- ### Convert JSON Schema String Constraints to Zod Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Applies string constraints such as `minLength`, `maxLength`, `pattern`, and `enum` from JSON Schema to Zod schemas. Useful for validating string length, format adherence via regex, and restricting values to a predefined set. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Pattern constraint const phoneSchema = JSONSchemaToZod.convert({ type: 'string', pattern: '^\+?[1-9]\d{1,14}$', }); phoneSchema.parse('+1234567890'); // ✓ phoneSchema.parse('abc'); // ✗ — does not match pattern // Enum constraint const colorSchema = JSONSchemaToZod.convert({ type: 'string', enum: ['red', 'green', 'blue'], }); colorSchema.parse('red'); // ✓ colorSchema.parse('yellow'); // ✗ — not in enum // Length constraints const usernameSchema = JSONSchemaToZod.convert({ type: 'string', minLength: 3, maxLength: 20, }); usernameSchema.parse('alice'); // ✓ ``` -------------------------------- ### Combinator Schemas: oneOf, anyOf, allOf Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Handles JSON Schema combinator keywords by producing Zod union or merged object schemas. `oneOf` and `anyOf` create unions, while `allOf` merges schemas into an intersection. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // oneOf — union of string or number const oneOfSchema = JSONSchemaToZod.convert({ oneOf: [{ type: 'string' }, { type: 'number' }], }); oneOfSchema.parse('hello'); // ✓ oneOfSchema.parse(42); // ✓ oneOfSchema.parse(true); // ✗ // anyOf — same union behaviour const anyOfSchema = JSONSchemaToZod.convert({ anyOf: [{ type: 'string' }, { type: 'number' }], }); anyOfSchema.parse('hi'); // ✓ // allOf — merges schemas (intersection) const allOfSchema = JSONSchemaToZod.convert({ allOf: [ { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, { type: 'object', properties: { age: { type: 'number' } }, required: ['age'] }, ], }); allOfSchema.parse({ name: 'Alice', age: 25 }); // ✓ // allOfSchema.parse({ name: 'Alice' }); // ✗ — age required ``` -------------------------------- ### Use JSON Schema Combinators with Zod Source: https://github.com/dmitryrechkin/json-schema-to-zod/blob/main/README.md Convert a JSON schema using combinators like `oneOf` into a Zod schema. This allows validation of data that can conform to multiple schema types. ```typescript const combinatorJsonSchema = { oneOf: [ { type: 'string' }, { type: 'number' }, ] }; const combinatorZodSchema = JSONSchemaToZod.convert(combinatorJsonSchema); // Validate data that can be of multiple types console.log(combinatorZodSchema.parse('Hello World')); // Output: "Hello World" console.log(combinatorZodSchema.parse(42)); // Output: 42 ``` -------------------------------- ### Number Constraints: multipleOf and enum Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Applies divisibility and enum constraints to number schemas. Ensure the input conforms to the specified `multipleOf` value or is present in the `enum` list. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // multipleOf const evenSchema = JSONSchemaToZod.convert({ type: 'number', multipleOf: 2 }); evenSchema.parse(4); // ✓ evenSchema.parse(3); // ✗ — not a multiple of 2 // numeric enum const prioritySchema = JSONSchemaToZod.convert({ type: 'number', enum: [1, 2, 3], }); prioritySchema.parse(2); // ✓ prioritySchema.parse(5); // ✗ — not in enum ``` -------------------------------- ### Convert JSON Schema String Formats to Zod Validators Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Converts JSON Schema `format` keywords into Zod's built-in format validators. Supports `email`, `date-time`, `uri`, `uuid`, and `date` formats. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; const emailSchema = JSONSchemaToZod.convert({ type: 'string', format: 'email' }); emailSchema.parse('user@example.com'); // ✓ emailSchema.parse('not-an-email'); // ✗ const uuidSchema = JSONSchemaToZod.convert({ type: 'string', format: 'uuid' }); uuidSchema.parse('550e8400-e29b-41d4-a716-446655440000'); // ✓ const urlSchema = JSONSchemaToZod.convert({ type: 'string', format: 'uri' }); urlSchema.parse('https://example.com'); // ✓ const dateSchema = JSONSchemaToZod.convert({ type: 'string', format: 'date' }); dateSchema.parse('2024-01-15'); // ✓ const datetimeSchema = JSONSchemaToZod.convert({ type: 'string', format: 'date-time' }); datetimeSchema.parse('2024-01-15T10:30:00Z'); // ✓ ``` -------------------------------- ### Convert JSON Schema to Zod Schema and Validate Data Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Use the `JSONSchemaToZod.convert` function to transform a JSON Schema object into a Zod schema. This schema can then be used for runtime data validation using `.parse()` or `.safeParse()`. Handles required fields and throws ZodError on invalid input. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Convert a flat object schema and validate data at runtime const schema = JSONSchemaToZod.convert({ type: 'object', properties: { name: { type: 'string' }, age: { type: 'number', minimum: 0 }, }, required: ['name', 'age'], }); // Valid input console.log(schema.parse({ name: 'Alice', age: 30 })); // Output: { name: 'Alice', age: 30 } // Invalid input — throws ZodError try { schema.parse({ age: 30 }); // missing required 'name' } catch (err) { console.error(err.errors); // [{ code: 'invalid_type', path: ['name'], message: 'Required' }] } ``` -------------------------------- ### Object Schema with additionalProperties Control Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Controls whether extra properties beyond the declared ones are allowed or must conform to a sub-schema. The default is strict, disallowing any additional properties. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Strict — no extra properties allowed (default) const strictSchema = JSONSchemaToZod.convert({ type: 'object', properties: { name: { type: 'string' } }, }); // strictSchema.parse({ name: 'Bob', extra: 1 }); // ✗ — extra key rejected // Passthrough — extra properties allowed const openSchema = JSONSchemaToZod.convert({ type: 'object', properties: { name: { type: 'string' } }, additionalProperties: true, }); openSchema.parse({ name: 'Bob', role: 'admin' }); // ✓ // Typed extra properties const typedExtrasSchema = JSONSchemaToZod.convert({ type: 'object', properties: { name: { type: 'string' } }, additionalProperties: { type: 'number' }, }); typedExtrasSchema.parse({ name: 'Bob', age: 30 }); // ✓ // typedExtrasSchema.parse({ name: 'Bob', age: 'old' }); // ✗ — extra must be number ``` -------------------------------- ### JSONSchemaToZod.convert(schema) Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt The primary function to convert a JSON Schema object into a Zod schema at runtime. This schema can then be used for data validation. ```APIDOC ## JSONSchemaToZod.convert(schema) ### Description Converts a JSON Schema object into a Zod schema that can be used for runtime data parsing and validation. ### Method `JSONSchemaToZod.convert(schema: JSONSchema): ZodSchema` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - The JSON Schema definition to convert. ### Request Example ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; const schema = JSONSchemaToZod.convert({ type: 'object', properties: { name: { type: 'string' }, age: { type: 'number', minimum: 0 }, }, required: ['name', 'age'], }); console.log(schema.parse({ name: 'Alice', age: 30 })); ``` ### Response #### Success Response (ZodSchema) - Returns a Zod schema object that can be used for validation. #### Response Example ```typescript // Example of a parsed object (successful validation) // { name: 'Alice', age: 30 } // Example of ZodError (failed validation) // [{ code: 'invalid_type', path: ['name'], message: 'Required' }] ``` ``` -------------------------------- ### Handle Complex Nested JSON Schemas Source: https://github.com/dmitryrechkin/json-schema-to-zod/blob/main/README.md Convert a complex JSON schema with nested objects and string formats like 'email' into a Zod schema. Useful for validating intricate data structures. ```typescript const complexJsonSchema = { type: 'object', properties: { name: { type: 'string' }, contact: { type: 'object', properties: { email: { type: 'string', format: 'email' }, phone: { type: 'string', pattern: '^\+?[1-9]\d{1,14}$' } }, required: ['email'] }, }, required: ['name'], }; const complexZodSchema = JSONSchemaToZod.convert(complexJsonSchema); // Validate complex data structures dynamically const complexParsedData = complexZodSchema.parse({ name: 'Jane Doe', contact: { email: 'jane.doe@example.com', phone: '+1234567890', }, }); console.log(complexParsedData); // Output: { name: 'Jane Doe', contact: { email: 'jane.doe@example.com', phone: '+1234567890' } } ``` -------------------------------- ### Conditional Validation with JSON Schema and Zod Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt Use `if`/`then`/`else` in JSON Schema for conditional validation. The library applies default values before condition evaluation. Ensure correct country-specific postal code patterns. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Postal code format varies by country const addressSchema = JSONSchemaToZod.convert({ type: 'object', properties: { country: { default: 'United States of America', enum: ['United States of America', 'Canada'] }, postal_code: { type: 'string' }, }, if: { properties: { country: { const: 'United States of America' } } }, then: { properties: { postal_code: { pattern: '[0-9]{5}(-[0-9]{4})?' } } }, else: { properties: { postal_code: { pattern: '[A-Z][0-9][A-Z] [0-9][A-Z][0-9]' } } }, }); addressSchema.parse({ country: 'United States of America', postal_code: '90210' }); // ✓ addressSchema.parse({ country: 'Canada', postal_code: 'K1A 0B1' }); // ✓ // addressSchema.parse({ country: 'Canada', postal_code: '90210' }); // ✗ ``` ```typescript // Nested conditionals — payment method determines required fields const paymentSchema = JSONSchemaToZod.convert({ type: 'object', properties: { paymentMethod: { type: 'string', enum: ['credit_card', 'bank_transfer', 'paypal'] }, creditCardNumber: { type: 'string' }, bankAccount: { type: 'string' }, paypalEmail: { type: 'string', format: 'email' }, }, required: ['paymentMethod'], if: { properties: { paymentMethod: { const: 'credit_card' } } }, then: { required: ['creditCardNumber'] }, else: { if: { properties: { paymentMethod: { const: 'bank_transfer' } } }, then: { required: ['bankAccount'] }, else: { required: ['paypalEmail'] }, }, }); paymentSchema.parse({ paymentMethod: 'credit_card', creditCardNumber: '4111111111111111' }); // ✓ paymentSchema.parse({ paymentMethod: 'paypal', paypalEmail: 'pay@example.com' }); // ✓ // paymentSchema.parse({ paymentMethod: 'paypal' }); // ✗ ``` -------------------------------- ### Inferring Schema Types from Keywords Source: https://context7.com/dmitryrechkin/json-schema-to-zod/llms.txt When `type` is omitted in a JSON Schema, the library infers the shape. An empty schema becomes `z.any()`, properties without a type default to an object, and combinators like `oneOf` create union schemas. ```typescript import { JSONSchemaToZod } from '@dmitryrechkin/json-schema-to-zod'; // Empty schema → z.any() const anySchema = JSONSchemaToZod.convert({}); anySchema.parse('anything'); // ✓ anySchema.parse(42); // ✓ anySchema.parse(null); // ✓ ``` ```typescript // Properties present but no type → treated as object const implicitObject = JSONSchemaToZod.convert({ properties: { name: { type: 'string' }, age: { type: 'number' }, }, required: ['name'], }); implicitObject.parse({ name: 'Bob', age: 40 }); // ✓ // implicitObject.parse({ age: 40 }); // ✗ — name is required ``` ```typescript // Combinators without type → union schema const implicitUnion = JSONSchemaToZod.convert({ oneOf: [{ type: 'string' }, { type: 'number' }], }); implicitUnion.parse('text'); // ✓ implicitUnion.parse(99); // ✓ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.