Home › Developer Tools › JSON to Zod Schema

JSON to Zod Schema

Paste sample JSON, such as an API response or a form payload, and get a ready-to-use Zod schema with nested object schemas, arrays, .optional() and .nullable() detected from your data and exported z.infer types. Switch to Zod 3 or Yup with one click. Everything runs in your browser.

Last updated:

Your JSON is parsed locally in this tab and never uploaded. Tip: Ctrl + Enter generates.

Advertisement
Advertisement

How to use the JSON to Zod Schema

  1. Paste sample JSON into the left box or open a .json file. If you have several examples, paste them as an array so optional keys can be detected.
  2. Name the root schema, for example user, which produces userSchema and the type User.
  3. Choose the library (Zod 4, Zod 3 or Yup) and whether nested objects get their own named schemas.
  4. Set the options: optional detection, type exports, .int(), string formats and strict objects.
  5. Copy or download the schema and validate data with userSchema.safeParse(data).

Example: infer a Zod schema from JSON

Pasting two sample orders as an array lets the generator see that coupon is sometimes missing and note is sometimes null:

[ { "id": 1, "email": "[email protected]", "total": 19.99, "note": null, "items": [ { "sku": "A1", "qty": 2 } ] },
  { "id": 2, "email": "[email protected]", "total": 5, "note": "Gift", "coupon": "SAVE10", "items": [] } ]

With the root name order and Zod 4 selected, the result is:

import { z } from 'zod';

export const itemSchema = z.object({
  sku: z.string(),
  qty: z.number().int(),
});

export const orderSchema = z.object({
  id: z.number().int(),
  email: z.email(),
  total: z.number(),
  note: z.string().nullable(),
  items: z.array(itemSchema),
  coupon: z.string().optional(),
});

export const orderListSchema = z.array(orderSchema);

export type Item = z.infer<typeof itemSchema>;
export type Order = z.infer<typeof orderSchema>;
export type OrderList = z.infer<typeof orderListSchema>;

How JSON values map to Zod and Yup

Sample valueZod 4Zod 3Yup
"text"z.string()z.string()yup.string()
"[email protected]"z.email()z.string().email()yup.string().email()
"2024-05-01T09:30:00Z"z.iso.datetime()z.string().datetime()yup.string().datetime()
42z.number().int()z.number().int()yup.number().integer()
4.5z.number()z.number()yup.number()
truez.boolean()z.boolean()yup.boolean()
[ … ]z.array(…)z.array(…)yup.array().of(…)
{}z.record(z.string(), z.unknown())z.record(z.unknown())yup.object()
Value or null.nullable().nullable().nullable().defined()
Key missing sometimes.optional().optional()(no .required())

Tips for better schemas

  • Use several samples. One object cannot show which keys are optional. Paste an array of real responses, including edge cases such as empty lists and null values.
  • Tighten the result by hand. Inference only sees your sample. Add constraints you know about, such as .min(1), .max(100), .positive() or z.enum(['draft', 'published']) for fixed sets of values.
  • Parse at the boundary. Call schema.parse() or safeParse() where untrusted data enters your app (API responses, form submissions, environment variables) and use the inferred type everywhere else.
  • Need a language-neutral schema? Use the JSON Schema Generator for a draft 2020-12 JSON Schema instead.

Frequently asked questions

How does the generator decide what is optional or nullable?

It reads every value in your sample. A key that is missing from some objects in an array becomes .optional(), a value that is null somewhere becomes .nullable(), and a value that is both becomes .nullish(). With a single object nothing can be missing, so for best results paste an array of several real examples. You can also mark every field optional.

What is the difference between the Zod 4 and Zod 3 output?

Zod 4 has top-level string formats, so an email is z.email(), a URL z.url() and an ISO timestamp z.iso.datetime(), and z.record() takes a key and a value schema. Zod 3 uses the method style, such as z.string().email() and z.string().datetime(). Everything else, including z.object, z.array and z.infer, is the same.

How do I get a TypeScript type from the schema?

With Export z.infer type on, every named schema gets a matching type, for example export type User = z.infer<typeof userSchema>. The type is derived from the schema, so you only maintain one source of truth. For Yup the generator writes yup.InferType<typeof userSchema>.

Why is a field typed z.null() or z.union()?

If a value is null everywhere in the sample, its real type cannot be inferred, so the schema accepts only null; replace it with something like z.string().nullable() once you know. If a field holds different types in different places, such as a string in one item and a number in another, the generator writes z.union([...]) with each type it saw.

Are string formats like email and UUID always detected?

A format is only added when every string value of that field matches it, for example every value looks like an email address. Dates must be full ISO 8601 timestamps such as 2024-05-01T09:30:00Z (with { offset: true } when the sample uses +02:00 style offsets). Turn format detection off if your real data may not always follow the format.

Does Yup support everything Zod does?

Most of it. Yup has no union type, so mixed-type fields become yup.mixed(). Required fields use .required(), null-able but present fields use .nullable().defined(), and missing keys are left optional, which is Yup's default.

Is my JSON uploaded?

No. Your JSON is parsed and the schema is generated by JavaScript in this page. Nothing is sent to a server.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON to TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON Schema GeneratorTurn sample JSON into a draft 2020-12 JSON Schema with types, required fields and formats.JSON ValidatorCheck JSON with the exact line and column of each error, fix tips and one-click auto-fix.JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.QR Code GeneratorMake QR codes for links, Wi-Fi, email and more.Barcode GeneratorCreate Code 128, EAN-13, UPC-A, EAN-8, Code 39 and ITF-14 barcodes as PNG or SVG.UUID GeneratorGenerate UUID v4 and v7 / GUIDs in bulk and copy or download them.Schema Markup Generator (JSON-LD)Create JSON-LD structured data for FAQ, Product, Article and more.Htaccess & Nginx Redirect GeneratorBuild 301 redirects for .htaccess, Nginx and Netlify or Cloudflare _redirects.Fake Data GeneratorGenerate mock data as JSON, CSV or SQL.Random String GeneratorGenerate secure random strings and tokens in bulk with any length and character set.API Key GeneratorCreate secure API keys and secrets with prefixes, checksums and SHA-256 hashes for storage.MIME Type LookupFind the MIME type for any file extension, or the extensions for a MIME type, in 400+ entries.Cron Expression GeneratorBuild crontab schedules visually, read them in plain English and see the next run times.URL Slug GeneratorTurn titles into clean, SEO-friendly URL slugs: accents, stop words, separators and bulk lines.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.License GeneratorCreate a LICENSE file for MIT, Apache, GPL, BSD, ISC, MPL or Unlicense with your name and year.ULID GeneratorGenerate sortable ULIDs and UUID v7 in bulk, monotonic option, and decode their timestamps.Htpasswd GeneratorCreate .htpasswd entries with bcrypt, APR1-MD5 or SHA-1 for Apache and Nginx basic auth.Placeholder Image GeneratorCreate placeholder images in any size, color and text as PNG, JPG, WebP, SVG or data URI.Ads.txt GeneratorCreate or validate ads.txt and app-ads.txt files: seller lines, cert IDs and variables.Docker Run to Compose ConverterConvert docker run commands to docker-compose.yml, or a compose file back to docker run.Dockerfile GeneratorGenerate a production Dockerfile and .dockerignore for Node, Python, Go or a static nginx site.HTML Boilerplate GeneratorTick the options you need and get a clean HTML5 starter template with meta, OG tags and CSS reset.Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.LLMs.txt GeneratorBuild an llms.txt file for AI crawlers: summary and link sections, import from your sitemap.Nano ID GeneratorGenerate secure Nano IDs with custom alphabet, length and count, plus a collision calculator.Nginx Config GeneratorBuild an nginx server block: static site, SPA, reverse proxy or PHP, with SSL, gzip and redirects.OpenAPI / Swagger ViewerView OpenAPI 2/3 JSON or YAML as interactive API docs with validation and an endpoint list.package.json GeneratorFill a form and get a valid, npm-ready package.json with scripts, dependencies and checks.PKCE Code Challenge GeneratorGenerate an OAuth 2.0 PKCE code_verifier and S256 code_challenge, build auth URLs, verify pairs.README GeneratorFill in a form and get a polished README.md with badges, install, usage and license, live preview.Regex GeneratorBuild regular expressions visually from blocks or presets (email, date, phone) and test them live.Commit Message GeneratorBuild Conventional Commit messages with type, scope, body, breaking change and issue refs.Database Schema DesignerDesign tables and relationships visually, then export SQL for MySQL, PostgreSQL or SQLite.Docker Compose GeneratorBuild a docker-compose.yml with a form: services, ports, volumes, env, healthchecks and presets.Dummy File GeneratorCreate test files of an exact size in KB, MB or GB with zeros, random bytes or text.FFmpeg Command GeneratorPick a task and options, get the exact ffmpeg command with every flag explained.Pivot Table MakerBuild pivot tables from CSV or Excel by drag and drop: sum, count, average, charts, export.SQL Query BuilderBuild SELECT queries visually: joins, filters, GROUP BY, ORDER BY and LIMIT, as clean SQL.Truth Table GeneratorType a logic expression and get its full truth table, minterms and canonical DNF/CNF.TypeScript PlaygroundWrite TypeScript with live type checking, see the compiled JavaScript and run it in your browser.Article Schema GeneratorCreate Article, BlogPosting or NewsArticle JSON-LD with headline, authors, dates and images.Event Schema GeneratorCreate Event JSON-LD with dates, venue or online location, tickets, organizer and performers.Google Search Query BuilderBuild advanced Google searches with site:, filetype:, intitle:, exact phrases and date operators.HowTo Schema GeneratorCreate HowTo JSON-LD with steps, tools, supplies, total time and cost, then copy it.Htaccess GeneratorBuild an Apache .htaccess file: HTTPS, www, gzip, caching, error pages, IP blocks, hotlinks.HTML Email Template BuilderDrag and drop blocks to build a responsive, table-based HTML email with inline styles.Organization Schema GeneratorCreate Organization JSON-LD with logo, URL, contact points, address and social profiles.PIN GeneratorGenerate random 4, 6 or 8-digit PINs that avoid sequences, repeats, dates and common PINs.Product Schema GeneratorBuild Product JSON-LD with price, availability, brand, GTIN, ratings and reviews.Question Keyword GeneratorFind the questions people ask about a topic, grouped by who, what, why, how, can and more.Recipe Schema GeneratorCreate Recipe JSON-LD with ingredients, steps, prep and cook times, nutrition and ratings.Security Headers GeneratorPick HSTS, CSP, frame, referrer and permissions options and get Apache, Nginx, Netlify or Cloudflare config.SKU GeneratorBuild consistent SKUs from brand, category, size and color, then export every variant as CSV.Typography Scale GeneratorBuild a modular type scale from a base size and ratio, then copy CSS variables or a Tailwind config.WordPress Salt GeneratorGenerate fresh WordPress security keys and salts for wp-config.php, .env or Docker in one click.ANSI Color Code GeneratorStyle terminal text with 16, 256 or RGB colors and get escape codes for bash, Python, JS and C.Apache Virtual Host GeneratorCreate an Apache VirtualHost config with SSL, redirects, reverse proxy or PHP-FPM in seconds.Bash Prompt GeneratorDrag and drop a custom PS1 prompt for bash or zsh with colors, git branch and a live preview.Changelog GeneratorTurn Conventional Commit messages into a grouped Keep a Changelog Markdown file per version.cURL Command BuilderBuild curl commands from a form: method, headers, query, JSON or form body, auth and flags.Docker Compose to KubernetesConvert docker-compose.yml into Kubernetes Deployment, Service, ConfigMap and PVC manifests.Docker Compose ValidatorCheck a docker-compose.yml for YAML errors, schema mistakes, broken references and deprecated keys.Dockerfile LinterLint a Dockerfile for best practices: pinned tags, apt cleanup, non-root USER and layer count.Dockerignore GeneratorBuild a .dockerignore from Node, Python, Go and Java templates, plus your own entries.ESLint Config GeneratorGenerate a flat eslint.config.js for JavaScript, TypeScript, React or Node with rule presets.Git Branch Name GeneratorTurn a ticket ID and title into a clean, valid git branch name like feature/PROJ-12-add-login.
See all 85 Code Generators & Builders →