Generate Zod Enums from JSON String Values

Learn how to create Zod enum schemas (z.enum()) from JSON fields that contain a fixed set of string values. Compare z.enum() with z.union() of literals.

Arrays

Detailed Explanation

Zod Enums from JSON Data

When a JSON field contains a small set of categorical string values, you can represent it as a Zod enum for both validation and autocompletion.

Example JSON

[
  { "id": 1, "status": "active" },
  { "id": 2, "status": "inactive" },
  { "id": 3, "status": "pending" }
]

Zod Enum Schema

import { z } from "zod";

const statusEnum = z.enum(["active", "inactive", "pending"]);

const accountSchema = z.object({
  id: z.number().int(),
  status: statusEnum,
});

type Status = z.infer<typeof statusEnum>;
// "active" | "inactive" | "pending"

z.enum() vs z.union() of Literals

Both approaches work, but z.enum() offers additional features:

// z.enum approach
const status = z.enum(["active", "inactive", "pending"]);
status.enum.active;    // "active" — runtime access to values
status.options;        // ["active", "inactive", "pending"]

// z.union approach
const status2 = z.union([
  z.literal("active"),
  z.literal("inactive"),
  z.literal("pending"),
]);
// No .enum or .options access

Native Enums

If you have an existing TypeScript enum, use z.nativeEnum():

enum Priority {
  High = "high",
  Medium = "medium",
  Low = "low",
}

const prioritySchema = z.nativeEnum(Priority);

Extracting and Excluding Values

const allStatus = z.enum(["active", "inactive", "pending", "banned"]);

// Subset
const activeStatus = allStatus.extract(["active", "pending"]);

// Exclude
const inactiveStatus = allStatus.exclude(["active"]);

When to Use z.enum()

  • The field accepts a fixed, known set of string values.
  • You want runtime access to the enum values (e.g., for dropdowns).
  • You need to extract or exclude values for different contexts.
  • Error messages should list the valid options automatically.

Use Case

You are building a filter dropdown for an order management dashboard and need both runtime access to all possible status values and compile-time type safety for the selected value.

Try It — JSON to Zod Schema

Open full tool