Validate JSON values with Zod

A practical review of using Zod to validate parsed JSON: what it checks, what it changes in your data, how errors read, and when plain JSON Schema or a syntax check is the better fit.

Zod is a TypeScript-first schema library. Teams often reach for it when JSON arrives from an API, a config file or a form and they need to confirm its shape before using it. This review covers what Zod validation does to a JSON payload, where it helps, and where a simpler tool is the better choice. No benchmark data, version-specific test results or measurements were supplied for this article. The guidance below rests on Zod's documented behavior and general JavaScript principles, and points that vary by Zod version are flagged.

Is Zod a good fit for validating JSON?

For TypeScript or JavaScript code that consumes JSON, Zod is a strong fit. Its main benefit is that one schema definition gives you both a runtime check and a static type, so the shape you validate and the shape your code assumes cannot drift apart. The decisive tradeoff is that the schema lives in your code. It is a JavaScript dependency, not a language-neutral contract, and by default it can return data that differs from the input.

A plain syntax check, a formatter, or a JSON Schema document is preferable in these cases:

  • You only need to know whether text is well-formed JSON. JSON.parse or a linter answers that without a schema.
  • You only need pretty-printing or minifying. That is formatting, not validation.
  • The contract must be shared with services written in other languages. JSON Schema or OpenAPI is the more portable artifact. Zod 4 documents a converter to JSON Schema, but treat converted output as something to review rather than assume is complete.
  • You need the validated output to be byte-for-byte the input. Zod's defaults strip unknown keys, and transforms change values, so you would have to configure it carefully or validate without using the returned data.

What Zod actually checks and changes

An ambiguity is worth clearing up first: Zod does not read JSON text. It validates JavaScript values. The usual flow has two separate steps. JSON.parse turns a string into a value and throws a SyntaxError if the text is malformed. A Zod schema then checks that value's structure and types. Keeping these steps distinct makes error handling clearer, because a syntax error and a shape error mean different things to the person fixing the input.

import { z } from "zod";

const User = z.object({
  id: z.number().int().positive(),
  name: z.string().min(1),
  tags: z.array(z.string()).default([]),
});

type User = z.infer<typeof User>;

function parseUser(text: string) {
  let data: unknown;
  try {
    data = JSON.parse(text);
  } catch {
    return { ok: false as const, error: "Invalid JSON syntax" };
  }

  const result = User.safeParse(data);
  if (!result.success) {
    return { ok: false as const, issues: result.error.issues };
  }
  return { ok: true as const, value: result.data };
}

The parse and safeParse methods differ only in how they report failure. The parse method throws, and safeParse returns an object with a success flag. In both cases the successful result is a new value built from the schema, not the original object passed through unchanged. That distinction drives most of the surprises:

Schema behavior | Effect on the returned data | Changes values?
Type and constraint checks (number, string, min, int) | Accepts or rejects the input; no rewriting | No
Default object handling | Keys not declared in the schema are dropped from the output | Yes
Strict object mode | Undeclared keys cause a validation failure instead of being dropped | No (rejects instead)
Passthrough or loose object mode | Undeclared keys are kept in the output | No
.default() | Fills in a value when the field is undefined | Yes
z.coerce | Converts input, for example a string to a number or date, before checking | Yes
.transform() | Replaces the value with whatever the function returns; output type can differ from input type | Yes

The method names for strict and loose objects differ between versions. Zod 3 uses .strict() and .passthrough() on an object schema. Zod 4 adds z.strictObject() and z.looseObject() as the preferred forms. Check the documentation for the version you install.

Here is how the schema above treats an illustrative input. Given {"id": 7, "name": "Ada", "role": "admin"}, validation succeeds and returns {"id": 7, "name": "Ada", "tags": []}. The undeclared role key is stripped and tags receives its default. Given {"id": "7", "name": "Ada"}, validation fails, because the string "7" is not a number and z.number() does not coerce. Both outcomes follow from the documented behavior in the table. If silently dropping role would hide a problem, such as a client sending a field the server ignores, use strict mode instead.

JSON also has no native date, undefined or bigint type. A timestamp arrives as a string. You can either validate it as a string in ISO datetime format or coerce it into a Date. Validating as a string keeps the value JSON-serializable. Coercing gives your code a Date object, but the output no longer round-trips through JSON.stringify as the same value without conversion. Zod 4 also documents a z.json() schema for any JSON-compatible value, which is useful as a guard for loosely typed fields. Confirm it exists in your installed version before relying on it.

Will the validated data and its errors stay usable?

Values produced by type checks alone serialize back to JSON cleanly. Usability problems come from the value-changing features. Output from transforms, coercion to Date, or Map and Set types may not serialize the way you expect, and stripped keys are gone for good. If the validated data is stored or forwarded, decide whether the original text or the validated output is the record of truth. Keeping the raw input alongside the result is the safer choice when auditing matters.

Each failure is reported as an issues array. Every issue carries a code such as invalid_type, a path to the offending field such as ["id"] or ["tags", 2], and a message. The path is the most useful part for readers, because it pinpoints the field even in deeply nested JSON. Default message wording changed between Zod 3 and Zod 4. Avoid matching on message text in tests or client code; match on code and path instead.

Raw issue arrays are developer-facing. If people will see the errors, for example in form validation, map each path to a field label and write your own messages. Both versions provide helpers that group issues by field: error.flatten() and error.format() in Zod 3, and z.flattenError() and z.treeifyError() in Zod 4. How those messages are presented to screen readers depends on your UI code, not on Zod. No assistive-technology testing was supplied for this article, so that part needs its own check in your interface.

Gaps in this review

  • No performance measurements were supplied, so this review makes no claims about validation speed or bundle size for any Zod version.
  • No hands-on test results were supplied. The behaviors above are drawn from Zod's documented API and should be confirmed against the version in your lockfile.
  • The accuracy of JSON Schema conversion was not evaluated. Review any generated schema before sharing it as a cross-language contract.