Convert a Simple JSON Object to a Zod Schema

Learn how to convert a flat JSON object into a Zod validation schema with z.string(), z.number(), z.boolean(), and z.null() validators.

Basic Types

Detailed Explanation

From JSON to a Zod Schema

The most common conversion is turning a simple, flat JSON object into a Zod z.object() schema. Each key in the JSON object becomes a field, and the value determines the Zod validator.

Example JSON

{
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com",
  "isActive": true,
  "score": 98.5
}

Generated Zod Schema

import { z } from "zod";

const userSchema = z.object({
  id: z.number().int(),
  name: z.string(),
  email: z.string(),
  isActive: z.boolean(),
  score: z.number(),
});

type User = z.infer<typeof userSchema>;

How the Mapping Works

Zod provides a validator for every JSON primitive:

JSON type Zod validator
string z.string()
integer z.number().int()
float z.number()
boolean z.boolean()
null z.null()

Unlike TypeScript interfaces that only exist at compile time, Zod schemas validate data at runtime. This means you get both type safety and runtime guarantees from a single definition.

The z.infer Trick

The z.infer<typeof schema> utility extracts the TypeScript type from a Zod schema. This eliminates the need to maintain separate type definitions — the schema becomes your single source of truth.

Best Practices

  • Use camelCase for schema variable names with a Schema suffix (e.g., userSchema, productDetailSchema).
  • Add method chains for validation constraints: z.string().email(), z.number().min(0), z.string().min(1).
  • Use z.infer to derive TypeScript types instead of writing them manually.

A simple flat object schema is the foundation. Once you are comfortable with this, nested objects, arrays, and refinements are natural next steps.

Use Case

You receive a JSON payload from a REST API and want both compile-time type safety and runtime validation to catch malformed data before it reaches your business logic.

Try It — JSON to Zod Schema

Open full tool