runtime validation · Zod v3+

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.

JSON → Zod Workspace
Input size
186 B
10 lines
Output size
419 B
3 schemas
Root name
schema
export const
Status
Valid
Zod v3+
Schema name
input · json sample
output · zod schema
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>;
Step-by-step Tutorial

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.

  1. 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.object tree from the shape of the data, so the richer your sample the better the produced validators.

    If a field can be null or 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 inferenceOpenAPI
    input · json sample2 keys
    {"name":"Ada","age":36}
    21 B · 1 linevalid · loaded
  2. 02

    Name your schema

    Defaults to schema. Pick something domain-specific like userSchema or webhookPayloadSchema. Nested objects get prefixed camelCase names (userSchemaAddress) so each sub-shape is independently importable.

    The generator also emits a matching z.infer type alias in PascalCase (type UserSchema = z.infer<typeof userSchema>) — one declaration, one runtime validator, one compile-time type.

    export constcamelCasez.inferPascalCase aliasnested schemas
    naming · schema → userSchemacamelCase
    export const userSchema = z.object({...});
    export type UserSchema = z.infer<typeof userSchema>;
    88 B · 2 linesschema + type · ready
  3. 03

    Review inferred Zod helpers

    Strings → z.string(), integers → z.number().int(), floats → z.number(), booleans → z.boolean(), arrays → z.array(...), nested objects → named z.object(...). Null becomes z.null(); empty arrays default to z.array(z.unknown()).

    For production constraints, hand-edit to add .nullable(), .optional(), .min()/.max(), .email(), .uuid(), or z.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 v3
    export const userSchema = z.object({
      name: z.string(),
      age: z.number().int(),
    });
    76 B · 4 linesZod v3+ · ready
  4. 04

    Use parse vs safeParse at runtime

    Call schema.parse(data) on any incoming value to validate and narrow at once — failures throw a detailed ZodError with 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.infer type lets the rest of your codebase consume the validated value with full IDE autocomplete and no any-casts.

    schema.parseschema.safeParseZodErrorz.infertype-safe
    usage · safeParsevalidated
    const data = await fetch(...).then(r => r.json());
    const user = userSchema.parse(data);
    // user: { name: string; age: number }
    production-readyZod v3+ · success
Pro tips

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.

Use Cases

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 responses

Webhook 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 payloads

Form / 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 safety

TRPC / 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 validation

Background 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-friendly

Test 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 confidence
FAQ

Frequently asked questions

About generating Zod schemas from JSON.

Zod is a TypeScript-first schema validation library. Define schemas once, get both runtime parse/validation and compile-time type inference.
Yes. Nested objects generate nested z.object() schemas. Arrays use z.array() with the inferred item schema.
Yes — paste into a TypeScript project with npm install zod. The import { z } from "zod" line is included.
The generator can't infer absence from a single sample. Add .nullable() for null-able and .optional() for sometimes-missing fields manually.
No. Parsing and codegen run locally — open DevTools → Network to confirm.
Suggest a tool

Something missing?

Tell us what you need. We ship the top requests every two weeks.

Sent straight to the maintainers · no account needed
47 in queue·8 shipped this month
Request queued. Thanks!