Generate Zod schemas from any JSON
Paste a JSON sample and get a ready-to-import Zod schema with inferred types. Validate API responses at runtime in seconds.
import { z } from "zod";
export const schemaUserAddress = z.object({
city: z.string(),
country: z.string(),
});
export const schemaUser = z.object({
name: z.string(),
age: z.number().int(),
active: z.boolean(),
roles: z.array(z.string()),
address: schemaUserAddress,
});
export const schema = z.object({
user: schemaUser,
version: z.number().int(),
});
export type Schema = z.infer<typeof schema>;How to generate a Zod schema from JSON
Zod is a TypeScript-first runtime validation library. Paste a JSON sample, get an idiomatic z.object tree with sub-schemas for every nested type and a typed z.infer alias ready to use throughout your codebase.
- 01
Paste a representative JSON sample
Use a real example — an API response, webhook payload, OpenAPI schema instance, or config file. The generator infers a
z.objecttree from the shape of the data, so the richer your sample the better the produced validators.If a field can be
nullor omitted in production, include at least one sample row where it is — single-sample inference can't see what isn't there.Need to clean a malformed payload first? Run it through JSON Repair, then come back.
API responsewebhook payloadconfigsingle-sample inferenceOpenAPIinput · json sample2 keys{"name":"Ada","age":36}21 B · 1 linevalid · loaded - 02
Name your schema
Defaults to
schema. Pick something domain-specific likeuserSchemaorwebhookPayloadSchema. Nested objects get prefixed camelCase names (userSchemaAddress) so each sub-shape is independently importable.The generator also emits a matching
z.infertype alias in PascalCase (type UserSchema = z.infer<typeof userSchema>) — one declaration, one runtime validator, one compile-time type.export constcamelCasez.inferPascalCase aliasnested schemasnaming · schema → userSchemacamelCaseexport const userSchema = z.object({...}); export type UserSchema = z.infer<typeof userSchema>;88 B · 2 linesschema + type · ready - 03
Review inferred Zod helpers
Strings →
z.string(), integers →z.number().int(), floats →z.number(), booleans →z.boolean(), arrays →z.array(...), nested objects → namedz.object(...). Null becomesz.null(); empty arrays default toz.array(z.unknown()).For production constraints, hand-edit to add
.nullable(),.optional(),.min()/.max(),.email(),.uuid(), orz.union([...])for discriminated shapes..refine()handles business rules the inference can't see.Cross-link: pair with JSON to TypeScript if you only need types, or JSON Schema for language-agnostic validation.
z.objectz.unionz.array.nullable().refine()output · zod schema.ts · valid Zod v3export const userSchema = z.object({ name: z.string(), age: z.number().int(), });76 B · 4 linesZod v3+ · ready - 04
Use parse vs safeParse at runtime
Call
schema.parse(data)on any incoming value to validate and narrow at once — failures throw a detailedZodErrorwith the exact path that failed (err.issues[0].path).Prefer
schema.safeParse(data)in production code: it returns a discriminated{ success: true, data }or{ success: false, error }union, so you handle malformed input without try/catch.The matching
z.infertype lets the rest of your codebase consume the validated value with full IDE autocomplete and no any-casts.schema.parseschema.safeParseZodErrorz.infertype-safeusage · safeParsevalidatedconst data = await fetch(...).then(r => r.json()); const user = userSchema.parse(data); // user: { name: string; age: number }production-readyZod v3+ · success
Production-grade Zod schemas, the right way
Use safeParse in production
Returns a discriminated union instead of throwing. Handles malformed input without try/catch.
Add .nullable() manually
If a field can be null in production but isn't in your sample, add .nullable() to the schema.
Optional vs nullable
.optional() = field can be missing. .nullable() = field can be null. They're different — use both for ?: T | null.
Constraints & refinements
Add .min(0), .max(255), .email(), .uuid(), or .refine() for business rules.
Bundle size
Zod is tree-shakeable. For very small bundles, evaluate valibot or typia alternatives.
Pair with TRPC / Server Actions
Zod schemas double as TRPC input validators and Next.js Server Action argument validators.
When to reach for Zod
Anywhere you want compile-time TypeScript types AND runtime validation from one declaration.
API response validation
Validate every fetch response before trusting its shape. Catches API drift before it crashes downstream. Output round-trips losslessly through JSON.parse + JSON.stringify, so the file you save is byte-identical to what you see. Streaming parsers, jq pipelines, and Postgres jsonb columns all accept the result without complaint.
fewer untyped responsesWebhook handlers
Stripe, Slack, GitHub, Shopify all post JSON. Validate the payload before touching anything else. Pairs perfectly with sort-keys + diff for review-friendly fixtures in CI. Whitespace-only churn disappears and reviewers see real changes, which keeps PR comments focused on logic rather than indentation.
validated payloadsForm / config parsing
Validate env vars, feature flags, and user input. Default with sensible errors instead of crashing later. Handles emoji and non-ASCII via UTF-8 throughout — your data survives copy-paste between editors, terminals, and IDEs. Combining marks and ZWJ sequences come out the other side intact.
input safetyTRPC / Server Actions
Schemas double as TRPC input validators and Next.js Server Action argument types — one source of truth. Re-parses on every keystroke so syntax errors are caught at the exact character. Strict RFC 8259 — no trailing commas, no comments, no unquoted keys — keeps downstream parsers happy.
DRY validationBackground job payloads
Validate job arguments at queue intake and at worker pickup — surfaces bad jobs before processing. Streams large documents without a server round-trip — privacy stays in the tab. Heavy parsing runs through useMemo so even 5 MB payloads keep the editor responsive.
schema-friendlyTest fixture validation
Run your test fixtures through the same schema as production data to catch drift. Output is byte-stable: same input plus same options always produces identical bytes, ideal for content-addressed caches and snapshot tests. Downloads ship with the application/json MIME so editors apply syntax highlighting.
test confidenceFrequently asked questions
About generating Zod schemas from JSON.
npm install zod. The import { z } from "zod" line is included..nullable() for null-able and .optional() for sometimes-missing fields manually.Something missing?
Tell us what you need. We ship the top requests every two weeks.