JSON to Zod Schema: From API Response to Runtime Validation

October 1, 2026  |  9 min read  |  TypeScript

By Syed · Frontend Engineer & Creator of UITweak

Writing Zod schemas by hand for a large, nested JSON payload is tedious, repetitive, and error-prone. You already have the perfect specification sitting in front of you: a real API response. The practical workflow is simple. Paste the JSON, generate the schema, validate at runtime, and let z.infer hand you the TypeScript types for free. This guide walks through that entire workflow with copy-paste code.

Shortcut: paste any JSON into our free JSON Converter, switch to the Zod tab, and copy a ready-to-use schema with format detection built in.

1. The 60-Second Workflow

Every JSON to Zod conversion follows the same four steps, whether you use a generator or write it manually:

  1. Capture a real response. Copy an actual API response, not a guessed shape. Real data reveals nesting, arrays, and nulls you would otherwise miss.
  2. Generate the base schema. Convert each JSON type to its Zod equivalent: strings to z.string(), numbers to z.number(), booleans to z.boolean(), objects to z.object(), arrays to z.array().
  3. Tighten the validators. Add format checks where the data has a known shape: emails, UUIDs, URLs, datetimes.
  4. Validate and infer. Parse responses with safeParse at runtime and derive your TypeScript types with z.infer.

2. What a Good Generated Schema Looks Like

Take a typical user object from an API. A solid Zod schema mirrors the JSON structure one to one, with nested objects pulled out into their own named schemas so the result stays readable:

import { z } from "zod";

const AddressSchema = z.object({
  city: z.string(),
  zip: z.string(),
});

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  age: z.number().int(),
  active: z.boolean(),
  address: AddressSchema,
  tags: z.array(z.string()),
});

export type User = z.infer<typeof UserSchema>;

Notice the last line. That single z.infer gives you a TypeScript type that always matches the schema. Change the schema and the type follows. This is the core reason teams pick Zod over plain interfaces: one source of truth for both compile-time types and runtime validation. If you only need static types, our JSON to TypeScript guide covers the interface route.

3. Format Detection: Strings Are Not Just Strings

A naive converter turns every string into z.string() and calls it done. That works, but it throws away information. A good conversion inspects the value and picks the right validator:

  • "550e8400-e29b-41d4-a716-446655440000" matches the UUID pattern, so it becomes z.string().uuid().
  • "ana@example.com" becomes z.string().email().
  • "https://api.example.com" becomes z.string().url().
  • "2026-10-01T10:00:00Z" becomes z.string().datetime().

These refinements catch an entire class of bugs at the boundary: a malformed id or an unexpected date format fails validation immediately instead of exploding three functions later. Our converter applies this detection automatically in the Zod tab.

4. Numbers, Nulls, and Empty Arrays

Three edge cases separate a decent schema from a reliable one. First, integers versus floats: an age of 30 should be z.number().int(), while a score of 4.5 stays z.number(). Second, explicit nulls: if the API genuinely returns null, model it as z.null() rather than pretending the field is always present. Third, empty arrays carry no type information, so z.array(z.unknown()) is the honest fallback until you see real items.

5. Optional vs Nullable: The Distinction That Matters

Generated schemas usually mark every observed field as required, but real APIs are messier. Learn the two modifiers because they answer different questions:

  • .optional() means the key may be absent from the object entirely.
  • .nullable() means the key is present but its value may be null.

When a field is sometimes missing and sometimes null, chain them: z.string().nullable().optional(). Review the fields your API documents as optional after generating, and add the modifier. This five-minute pass prevents most production validation failures.

6. Validate at Runtime with safeParse

A schema only earns its keep when you actually run data through it. Never trust fetch responses blindly. Parse at the boundary where data enters your app:

const res = await fetch("https://api.example.com/user/1");
const json = await res.json();

const result = UserSchema.safeParse(json);

if (!result.success) {
  console.error("Invalid API response:", result.error.issues);
  throw new Error("Bad data from API");
}

// result.data is now fully typed as User
renderProfile(result.data);

safeParse returns a result object instead of throwing, which makes it ideal for API boundaries. On success, result.data is typed as User with zero type assertions. On failure, result.error.issues tells you exactly which field broke and why, which is far more useful than a cryptic runtime crash.

7. Zod 4 Note: JSON Schema to Zod Directly

If you already have a JSON Schema (not raw JSON), Zod 4 added native support for converting it: z.fromJSONSchema() builds a Zod schema straight from a JSON Schema document. Use it when an OpenAPI spec is your source of truth. When all you have is a sample response, the JSON to Zod workflow in this guide is still the fastest path.

8. Tool Comparison: Pick Your Path

Honest summary of the realistic options for getting from JSON to a Zod schema:

  • uitweak JSON Converter (Zod tab): free, runs in the browser, format detection included, also exports TypeScript, Go, Rust, Python, and more from the same input.
  • quicktype: mature multi-language converter, strong TypeScript output, but Zod is not its focus.
  • Dedicated Zod CLIs: handy for automation and watch modes, but another tool to install and learn.
  • Manual: full control, best for small schemas you want to hand-tune, impractical past a few dozen fields.

9. Frequently Asked Questions

Can Zod generate a schema from JSON automatically?

Zod itself does not ship a JSON to schema generator, but converters do exactly this: they walk your JSON and emit the matching z.object, z.array, and primitive validators. Generate first, then hand-tune optional fields and formats.

Should I use Zod or Yup for form and API validation?

Both validate at runtime, but Zod infers TypeScript types from the schema with z.infer, so types never drift from validation rules. If you work in TypeScript, Zod is the modern default.

Do I still need Zod if I already have TypeScript interfaces?

Yes, for anything crossing a network boundary. Interfaces vanish at compile time and cannot check a real API response. Zod validates at runtime, which is where bad data actually arrives.

Is a generated schema production-ready?

Almost. Treat generation as a 90 percent solution: review optional versus nullable fields, confirm format validators match your data, and add stricter rules (min lengths, enums, unions) where your domain needs them.

Try it now: open the free JSON Converter, paste an API response, hit the Zod tab, and copy your schema. Then validate every response with safeParse and never debug mystery API shapes again.

# Expansion draft: json-to-zod-schema-guide

Discriminated Unions: z.discriminatedUnion

The main guide mentions unions as a hand-tuning step. Zod has a dedicated method for the discriminated case, and it is worth using over a plain z.union: it validates faster (it looks up the schema by the discriminant value instead of trying each one) and it produces clearer error messages.

const ShapeSchema = z.discriminatedUnion("kind", [
  z.object({ kind: z.literal("circle"), radius: z.number() }),
  z.object({ kind: z.literal("square"), side: z.number() }),
]);

type Shape = z.infer<typeof ShapeSchema>;

The inferred type narrows on kind exactly like a hand-written discriminated union, so the never exhaustiveness check from our TypeScript guide works on it unchanged. One requirement: the discriminant values must be literals (z.literal), and every variant needs the same discriminant key. If your API discriminates on something messier, like the presence or absence of a field, fall back to z.union and accept the slower validation.

Readable Errors: treeifyError

Raw result.error.issues is built for machines. When validation fails in logs or forms, you want the readable form. In Zod 4 that is z.treeifyError:

const result = UserSchema.safeParse(json);

if (!result.success) {
  console.error(z.treeifyError(result.error));
  // { properties: { email: { errors: ["Invalid email address"] } } }
}

The tree mirrors your schema shape, so finding the broken field is visual. On Zod 3 the equivalents are result.error.format() and result.error.flatten(). I log the treeified form server-side and send flattened field errors to the client. Never ship raw issues to a user; paths like ["address", 0, "zip"] mean nothing outside your codebase.

Coercion at the Boundary: z.coerce

Query parameters and form data arrive as strings. ?page=2 gives you "2", and z.number() rejects it, which is technically correct and practically annoying. z.coerce runs the value through a constructor first:

const QuerySchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  active: z.coerce.boolean(), // "true" -> true, "false" -> false
});

Coerce only at boundaries where input is stringly typed: query strings, FormData, CSV imports. I never coerce inside a JSON API schema, where a string instead of a number is a real bug worth failing on. Used at the right boundary, z.coerce.number() deletes a whole class of parseInt plumbing. Used in the wrong place, it hides type errors.

Cross-Field Rules With superRefine

Single-field validators cannot express "these two fields must agree." Password confirmation is the classic case, and superRefine handles it by giving you the whole object plus an issue collector:

const SignupSchema = z
  .object({
    password: z.string().min(8),
    confirm: z.string(),
  })
  .superRefine((val, ctx) => {
    if (val.password !== val.confirm) {
      ctx.addIssue({
        code: "custom",
        message: "Passwords do not match",
        path: ["confirm"],
      });
    }
  });

The path: ["confirm"] is the detail that matters: it attaches the error to the confirmation field so your form UI puts the message in the right place. I reach for superRefine over .refine whenever a rule touches more than one field or needs a precise path. Keep refinements pure and fast; they run on every parse.

strict vs strip: Controlling Unknown Keys

By default z.object strips unknown keys, which is the right default for forward compatibility: the API adds a field, your app keeps working. Two cases for changing it: .strict() fails on unknown keys, which I use for request bodies my own client sends, where an extra key means a client bug. .passthrough() keeps unknown keys, useful for proxies forwarding data they do not fully understand.

const StrictBody = z.object({ name: z.string() }).strict();
StrictBody.safeParse({ name: "x", admin: true }); // fails: unrecognized key

Pick per schema, not per project. Response schemas strip, request schemas for your own API go strict, proxies pass through.

Recursive Schemas With z.lazy

Trees (categories, comments, org charts) reference themselves, which a plain z.object cannot express because the schema does not exist yet at the point of reference. z.lazy defers the lookup:

interface Category {
  name: string;
  children: Category[];
}

const CategorySchema: z.ZodType<Category> = z.object({
  name: z.string(),
  children: z.array(z.lazy(() => CategorySchema)),
});

The explicit z.ZodType<Category> annotation is required; without it TypeScript cannot resolve the circular inference. Real APIs send deeply nested trees, so I pair this with a depth guard: a malicious 10,000-deep payload will blow the call stack during parsing. Recursion in the schema mirrors recursion in the data, but the stack limit is still the stack limit.

Share this guide