or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# JSON Schema to Zod

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @n8n/json-schema-to-zod

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @n8n/json-schema-to-zod`

10

11

## Core Imports

12

13

```typescript

14

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

15

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

16

```

17

18

For CommonJS:

19

20

```javascript

21

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

22

```

23

24

## Basic Usage

25

26

```typescript

27

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

28

import { z } from "zod";

29

30

// Simple string schema

31

const jsonSchema = {

32

type: "string",

33

minLength: 3,

34

maxLength: 50

35

};

36

37

const zodSchema = jsonSchemaToZod(jsonSchema);

38

// Result: z.string().min(3).max(50)

39

40

// Complex object schema

41

const objectSchema = {

42

type: "object",

43

properties: {

44

name: { type: "string" },

45

age: { type: "number", minimum: 0 },

46

email: { type: "string", format: "email" }

47

},

48

required: ["name", "age"]

49

};

50

51

const zodObjectSchema = jsonSchemaToZod(objectSchema);

52

// Result: z.object({ name: z.string(), age: z.number().min(0), email: z.string().email().optional() })

53

54

// With options

55

const zodSchemaWithOptions = jsonSchemaToZod(jsonSchema, {

56

withoutDefaults: true,

57

withoutDescribes: true

58

});

59

```

60

61

## Capabilities

62

63

### Schema Conversion

64

65

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

66

67

```typescript { .api }

68

/**

69

* Converts a JSON schema object to a Zod schema

70

* @param schema - JSON schema object or boolean to convert

71

* @param options - Optional configuration for the conversion

72

* @returns Zod schema equivalent to the input JSON schema

73

*/

74

function jsonSchemaToZod<T extends z.ZodTypeAny = z.ZodTypeAny>(

75

schema: JsonSchema,

76

options?: JsonSchemaToZodOptions

77

): T;

78

```

79

80

**Usage Example:**

81

82

```typescript

83

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

84

import { z } from "zod";

85

86

// Array schema with validation

87

const arraySchema = {

88

type: "array",

89

items: { type: "string" },

90

minItems: 1,

91

maxItems: 10

92

};

93

94

const zodArray = jsonSchemaToZod<z.ZodArray<z.ZodString>>(arraySchema);

95

// Result: z.array(z.string()).min(1).max(10)

96

97

// Union schema (anyOf)

98

const unionSchema = {

99

anyOf: [

100

{ type: "string" },

101

{ type: "number" }

102

]

103

};

104

105

const zodUnion = jsonSchemaToZod(unionSchema);

106

// Result: z.union([z.string(), z.number()])

107

```

108

109

### Parser Override System

110

111

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

112

113

```typescript { .api }

114

/**

115

* Parser override function type for custom schema parsing

116

* @param schema - The JSON schema object being parsed

117

* @param refs - Reference tracking and options context

118

* @returns Custom Zod schema or undefined to use default parsing

119

*/

120

type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny | undefined;

121

```

122

123

**Usage Example:**

124

125

```typescript

126

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

127

import { z } from "zod";

128

129

const customParser = (schema, refs) => {

130

// Custom handling for string schemas with specific format

131

if (schema.type === "string" && schema.format === "uuid") {

132

return z.string().uuid();

133

}

134

// Return undefined to use default parsing

135

return undefined;

136

};

137

138

const schema = {

139

type: "string",

140

format: "uuid"

141

};

142

143

const zodSchema = jsonSchemaToZod(schema, {

144

parserOverride: customParser

145

});

146

// Result: z.string().uuid()

147

```

148

149

## Types

150

151

### Core Types

152

153

```typescript { .api }

154

/**

155

* Represents any serializable value

156

*/

157

type Serializable =

158

| { [key: string]: Serializable }

159

| Serializable[]

160

| string

161

| number

162

| boolean

163

| null;

164

165

/**

166

* Main JSON schema type - can be an object or boolean

167

*/

168

type JsonSchema = JsonSchemaObject | boolean;

169

170

/**

171

* JSON Schema object with all standard properties

172

*/

173

interface JsonSchemaObject {

174

// Type definition

175

type?: string | string[];

176

177

// Object properties

178

properties?: { [key: string]: JsonSchema };

179

additionalProperties?: JsonSchema;

180

unevaluatedProperties?: JsonSchema;

181

patternProperties?: { [key: string]: JsonSchema };

182

minProperties?: number;

183

maxProperties?: number;

184

required?: string[] | boolean;

185

propertyNames?: JsonSchema;

186

187

// Array properties

188

items?: JsonSchema | JsonSchema[];

189

additionalItems?: JsonSchema;

190

minItems?: number;

191

maxItems?: number;

192

uniqueItems?: boolean;

193

194

// String properties

195

minLength?: number;

196

maxLength?: number;

197

pattern?: string;

198

format?: string;

199

200

// Number properties

201

minimum?: number;

202

maximum?: number;

203

exclusiveMinimum?: number | boolean;

204

exclusiveMaximum?: number | boolean;

205

multipleOf?: number;

206

207

// Union/combination properties

208

anyOf?: JsonSchema[];

209

allOf?: JsonSchema[];

210

oneOf?: JsonSchema[];

211

212

// Conditional properties

213

if?: JsonSchema;

214

then?: JsonSchema;

215

else?: JsonSchema;

216

217

// Shared properties

218

const?: Serializable;

219

enum?: Serializable[];

220

errorMessage?: { [key: string]: string | undefined };

221

description?: string;

222

default?: Serializable;

223

readOnly?: boolean;

224

not?: JsonSchema;

225

contentEncoding?: string;

226

nullable?: boolean;

227

}

228

```

229

230

### Configuration Types

231

232

```typescript { .api }

233

/**

234

* Options for customizing the JSON schema to Zod conversion

235

*/

236

interface JsonSchemaToZodOptions {

237

/** Exclude default values from the generated Zod schema */

238

withoutDefaults?: boolean;

239

/** Exclude descriptions from the generated Zod schema */

240

withoutDescribes?: boolean;

241

/** Custom parser function for overriding default parsing behavior */

242

parserOverride?: ParserOverride;

243

/** Maximum parsing depth to prevent infinite recursion */

244

depth?: number;

245

}

246

247

/**

248

* Internal reference tracking type used during parsing

249

*/

250

interface Refs extends JsonSchemaToZodOptions {

251

/** Current parsing path for error reporting and debugging */

252

path: Array<string | number>;

253

/** Map for tracking seen objects to handle circular references */

254

seen: Map<object | boolean, { n: number; r: z.ZodTypeAny | undefined }>;

255

}

256

```

257

258

### Parser Function Types

259

260

```typescript { .api }

261

/**

262

* Parser selector function type for choosing appropriate parser

263

*/

264

type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny;

265

266

/**

267

* Parser override function type for custom schema parsing

268

*/

269

type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => z.ZodTypeAny | undefined;

270

```

271

272

## Supported JSON Schema Features

273

274

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

275

276

- **Primitive Types**: string, number, integer, boolean, null

277

- **Object Schemas**: properties, required fields, additional properties, pattern properties

278

- **Array Schemas**: items, additional items, length constraints, uniqueness

279

- **String Validation**: length constraints, patterns, format validation

280

- **Number Validation**: min/max values, exclusive bounds, multiple constraints

281

- **Union Types**: anyOf, oneOf, allOf combinations

282

- **Conditional Logic**: if/then/else schemas

283

- **Constants**: const and enum values

284

- **Descriptions**: schema documentation preservation

285

- **Default Values**: automatic default value application

286

- **Nullable Types**: nullable schema support

287

- **Circular References**: automatic detection and handling

288

- **Error Messages**: custom error message support

289

- **Read-only**: read-only property support

290

291

## Error Handling

292

293

The library handles various edge cases and validation scenarios:

294

295

- **Circular References**: Automatically detected and resolved using reference tracking

296

- **Invalid Schemas**: Graceful handling of malformed JSON schema objects

297

- **Type Mismatches**: Proper error reporting for incompatible schema definitions

298

- **Deep Nesting**: Depth control to prevent stack overflow on deeply nested schemas

299

- **Missing Dependencies**: Clear error messages when required Zod peer dependency is missing