okay so something i keep forgetting when i write a zod schema from an api response. one response is just one sample, and a schema made from one sample is only as honest as that sample.

say the api gives you a list of users and the first user has a phone key. the second one doesn't. if you only looked at the first item you'd write phone as a required string and then the second user blows up at runtime. so every item in the array has to be read, not just the first. the objects get merged into one schema and any key that some items lack becomes .optional(). null works the same way, a key that is null somewhere gets .nullable(), and if it is both missing in one item and null in another you want .nullish().

the string checks are where it gets tricky. adding .email() or .datetime() looks easy but it is only safe if every sample of that field matches. one date-time with the offset written +0530 and zod would reject it, so that field should stay a plain z.string(). i'd honestly rather have a loose schema than a strict one that throws on real data.

small example, this one is straight from the page:

{"id":7,"email":"a@example.com","joined":"2026-11-08T10:00:00Z","tags":["x"],"score":4.5,"site":"https://example.com","nick":null} 

that becomes a RootSchema with these fields, plus export type Root = z.infer

id: z.number() email: z.string().email() joined: z.string().datetime({ offset: true }) tags: z.array(z.string()) score: z.number() site: z.string().url() nick: z.null() 

see 7 and 4.5 are both z.number(), json has only one number type. and .int() only if you ask for it, because a sample of 7 doesn't tell you that 7.5 can never come.

a few more things the page says. a field holding different kinds of value becomes a z.union([...]). empty arrays become z.array(z.unknown()) and empty objects become z.record(z.string(), z.unknown()), because there is nothing to infer from, make sure you tighten those by hand okay. you can also pick one nested schema (inline) or one const per object shape (named), where identical shapes share one schema.

i built this one so ya, i'm biased. it runs in your browser and nothing you paste is sent anywhere. the output only uses calls that exist in zod 3.23 and later and in zod 4, and the tests run every case through the real zod library to check the schema accepts the sample it came from. just paste a real response of yours and see what it makes optional: https://theomnikit.com/dev/json-to-zod?utm_source=devto&utm_medium=article&utm_campaign=devto-json-to-zod

how do you handle a field that is a number in one response and a string in another? the tool makes it a union, but curious what you do about it.

i used an AI assistant to help draft this, the facts are from the tool page.