Capítulo 31 de 61

Chapter 31: JSON

Core Idea

z.json() is a convenience schema for "any JSON-encodable value" — a recursive union covering every JSON type.

Key Concepts

  • z.json(): validates any value that could round-trip through JSON.stringify/JSON.parse — string, number, boolean, null, array of JSON values, or a string-keyed record of JSON values.
  • Implemented as a recursive z.lazy() union: internally equivalent to a self-referential union of primitives, arrays, and records, built with z.lazy() to allow the recursive reference.

Code Examples

const jsonSchema = z.json();

// conceptually equivalent to:
const jsonSchemaExpanded = z.lazy(() =>
  z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.null(),
    z.array(jsonSchemaExpanded),
    z.record(z.string(), jsonSchemaExpanded),
  ])
);
  • What it demonstrates: z.json() is sugar over a recursive union you could otherwise hand-write.

Key Takeaways

  1. Use z.json() whenever a field must be "anything JSON-serializable" (e.g. a generic metadata blob), instead of hand-rolling the recursive union.
  2. Because it's recursive, z.json() can validate arbitrarily nested JSON structures, not just flat values.

Connects To

  • Recursive Objects: the same getter/lazy-reference pattern that makes self-referential schemas possible.
  • Records: the dictionary variant used internally for JSON object values.