Guides

Generating TypeScript, Zod & Pydantic v2 Schemas from JSON

Turn API JSON samples into strict TypeScript interfaces, runtime Zod validators, and Python Pydantic v2 BaseModels with optional & alias inference.

2 min read

Quick Answer: Generating `TypeScript` interfaces, runtime `Zod` schemas, and Python `Pydantic v2` models from a real JSON API payload catches missing keys and type drift at compile time and runtime. TxtTo infers union types, optional fields, and nested objects locally in memory without sending API payloads outward.

Why compile-time types alone aren't enough at API boundaries

TypeScript interfaces vanish during compilation. If an external webhook renames a key or returns `null` unexpectedly, TypeScript interfaces stay silent until runtime crashes occur.

Pairing static TypeScript models with runtime validators—Zod in JavaScript/TypeScript and Pydantic v2 in Python—guarantees end-to-end payload safety.

Inferring optional keys and union types in TypeScript

Real API arrays rarely include every optional property on element 0. JSON to TypeScript inspects every element in an object array, merging properties and automatically appending `?` on keys missing from some records.

ts
export interface EventItem {
  id: string;
  retries?: number;
  error: string | null;
}

Generate TypeScript interfaces from JSON

Runtime validation & z.infer with Zod

Instead of maintaining duplicate interfaces and validation logic, JSON to Zod emits nested `z.object(...)` validators alongside `export type RootSchema = z.infer<typeof rootSchema>` so runtime checks and static types stay synced.

Generate Zod validation schemas

Python Pydantic v2 BaseModel with Field aliases

JavaScript APIs speak `camelCase` while PEP 8 Python expects `snake_case`. JSON to Pydantic hoists nested models cleanly, generates `Optional[...]` hints, and attaches `Field(alias="camelKey")` automatically.

python
class RootModel(BaseModel):
    user_id: str = Field(alias="userId")
    is_active: bool = Field(alias="isActive")

Generate Pydantic v2 models locally

References

Frequently asked questions

What happens when a JSON key uses dashes or Python reserved words?

Property names are sanitized cleanly—TypeScript quotes invalid identifiers, and Pydantic maps them to safe snake_case attributes using Field(alias=...).

Should I enable strict objects in generated Zod schemas?

Enable Strict Objects when testing exact internal contracts; keep it off when consuming external third-party APIs that frequently add harmless extra fields.

Can I format or repair messy JSON before generating schemas?

Yes. Run payloads through JSON Formatter first to strip trailing commas and inspect the parsed tree, then click Continue with JSON to TypeScript.

Related formats

Related Comparisons

Related Guides