A CLI tool and library to convert JSON structures into Zod schemas — with optional .openapi({ example })
generation, perfect for tools like:
This feature saves significant time when transforming example JSON data into Zod + OpenAPI-compatible schemas.
- ✅ Automatic Zod Schema Generation — Infers types like
z.string()
,z.number()
,z.boolean()
,z.null()
,z.object()
, andz.array()
from any JSON. - 🔁 Recursive Type Inference — Handles deeply nested structures.
- 📦 Optional OpenAPI Examples — Add
.openapi({ example })
metadata with a flag or programmatically. - 💻 CLI Tool — Generate schemas from the command line via JSON input or piping.
- 📚 Library/API — Use the core logic in your JS/TS apps.
{
"name": "Jane",
"age": 25,
"tags": ["developer", "typescript"],
"settings": {
"darkMode": true
}
}
export const schema = z.object({
name: z.string(),
age: z.number(),
tags: z.array(z.string()),
settings: z.object({
darkMode: z.boolean()
})
});
Using the --add-openapi-examples
flag or { addOpenApiExamples: true }
programmatically:
export const schema = z.object({
name: z.string().openapi({ example: "Jane" }),
age: z.number().openapi({ example: 25 }),
tags: z.array(z.string().openapi({ example: "developer" })).openapi({ example: ["developer", "typescript"] }),
settings: z.object({
darkMode: z.boolean().openapi({ example: true })
}).openapi({ example: { darkMode: true } })
});
You can also use json2zod
directly in your browser via the live playground:
No installation needed — paste your JSON, configure options, and get your Zod schema instantly!
Install the package via npm:
npm install json2zod
# or globally
npm -g install json2zod
Or with your favorite package manager:
pnpm add json2zod
# or
bun add json2zod
After installing globally or using npx
:
npx json2zod '{"example": "json"}'
Or use directly from your project scripts.
For quick conversions:
json2zod '{"name": "Alice", "age": 30, "address": {"city": "New York"}}'
From a file:
cat data.json | json2zod
From stdin:
echo '{"item": "Book", "id": 123}' | json2zod
Add .openapi({ example })
metadata for each field:
cat your_data.json | json2zod --add-openapi-examples
This is useful for OpenAPI tools like:
Display usage and available flags:
json2zod --help
You can import the schema generator directly in your JS/TS project:
import { generateZodSchema } from 'json2zod';
const json = {
name: "Jane",
age: 25,
tags: ["developer", "typescript"],
settings: {
darkMode: true
}
};
// Without OpenAPI examples
console.log(generateZodSchema(json));
// With OpenAPI examples
console.log(generateZodSchema(json, { addOpenApiExamples: true }));
Supports arrays too:
const input = [
{ id: 1, title: "First" },
{ id: 2, title: "Second" }
];
console.log(generateZodSchema(input));
To contribute:
git clone https://github.com/Drarox/json2zod.git
cd json2zod
npm install
npm run build
MIT License — see the LICENSE file for details.