Convert JSON Arrays of Objects to Zod Array Schemas

Learn how to convert JSON arrays containing objects into Zod z.array() schemas with typed elements. Covers homogeneous and heterogeneous arrays.

Basic Types

Detailed Explanation

Typing Arrays with Zod

When JSON contains an array of objects, the converter inspects every element to determine a unified schema for the array items, then wraps it in z.array().

Example JSON

{
  "users": [
    { "id": 1, "name": "Alice", "role": "admin" },
    { "id": 2, "name": "Bob", "role": "editor" },
    { "id": 3, "name": "Carol", "role": "viewer" }
  ]
}

Generated Zod Schema

import { z } from "zod";

const usersItemSchema = z.object({
  id: z.number().int(),
  name: z.string(),
  role: z.string(),
});

const rootSchema = z.object({
  users: z.array(usersItemSchema),
});

type UsersItem = z.infer<typeof usersItemSchema>;
type Root = z.infer<typeof rootSchema>;

Array Validation Methods

Zod arrays support powerful validation chains:

// Minimum and maximum length
z.array(usersItemSchema).min(1).max(100)

// Non-empty array
z.array(usersItemSchema).nonempty()

// Exact length
z.array(usersItemSchema).length(3)

Primitive Arrays

Arrays of primitives map directly:

JSON Zod schema
[1, 2, 3] z.array(z.number())
["a", "b"] z.array(z.string())
[true, false] z.array(z.boolean())
[1, "two", true] z.array(z.union([z.number(), z.string(), z.boolean()]))

Mixed-Type Arrays

When an array contains elements of different types, Zod uses z.union() to accept any of them:

const mixedSchema = z.array(
  z.union([z.string(), z.number(), z.boolean()])
);

This validates that every element is one of the specified types, providing both flexibility and safety.

Use Case

You fetch a list of users from a paginated API endpoint and need to validate that every element in the array matches the expected schema before processing.

Try It — JSON to Zod Schema

Open full tool