JSON to TypeScript Converter

Paste a JSON sample and get TypeScript for it: an interface, type or class, a Zod, Valibot or TypeBox schema with its inferred type, or a JSON Schema. Nested objects get their own named types, optional fields are detected across array items, and null becomes a union. Messy JSON is repaired and big numbers stay exact. Everything runs in your browser.


        

How to convert JSON to TS

  1. Paste a real payload. Copy a response from the browser's Network tab, Postman or curl. JavaScript object literals and slightly broken JSON also work (unquoted keys, single quotes, trailing commas, comments), because the input is repaired before inference and every fix is listed under the tool.
  2. Name the root. Set Root name to the domain concept, such as User or OrderResponse. Nested types are named from their keys, so the whole set reads well.
  3. Pick the output. Interface or Type for plain type checking, Class if your code creates instances, Zod, Valibot or TypeBox if you also want to validate data at runtime, and JSON Schema for validators and API docs in any language.
  4. Review and copy. Check every optional field and every | null against your API docs, then copy the result or download it.

How the types are inferred

JSON carries no schema, so the converter works it out from the values it sees. The same inference runs for every output, so an optional field in the interface is also optional in the Zod schema and missing from required in the JSON Schema.

JSON sampleGenerated TypeScriptRule
"id": 7id: number;Strings, numbers and booleans map directly. JSON Schema output uses integer when every observed value is a whole number.
"owner": {"name": "Ada"}owner: Owner; and interface OwnerEach nested object becomes a named type in PascalCase. Identical shapes are reused, and a clash gets a suffix (Owner2).
"items": [{"sku": "A"}]items: Item[];Array item types are named from the singular of the key: items → Item, categories → Category.
[{"a": 1, "b": 2}, {"a": 3}]a: number; b?: number;A key missing from some array items becomes optional.
"note": null in one item, "x" in anothernote: string | null;Observed nulls are added to the union. Turn on null → optional to get note?: string | null.
[1, "two", true](string | number | boolean)[]Mixed primitive arrays become a union.
[]unknown[]There is nothing to infer from. Replace it with the real item type.
"my-key": 1"my-key": number;Keys that are not valid identifiers are quoted.
"id": 9007199254740993id: number; plus a warningThe number is kept exact while parsing, but it is past 253, so the tool warns you to type it as string or bigint.

Example: optional detection across array items

[
  { "sku": "A-1", "color": "red", "surcharge": 0 },
  { "sku": "A-2", "color": "blue" }
]

// generated
export interface Root {
  sku: string;
  color: string;
  surcharge?: number;   // present in item 0, missing in item 1
}

Choosing an output format

OutputLooks likeChoose it when
Interfaceexport interface User { id: number; }The default for object shapes. It can be extended and merged, and gives clear error messages.
Typeexport type User = { id: number; };Your codebase uses type everywhere, or you will combine shapes with unions and intersections.
Classexport class User { id!: number; }You create instances, use decorators (TypeORM, class-validator, NestJS DTOs) or want a JSON-to-TS “POJO” model.
Zodz.object({ id: z.number() })You want runtime validation with the biggest ecosystem of integrations.
Valibotv.object({ id: v.number() })You validate in the browser or at the edge and want the bundle to contain only the validators you use.
TypeBoxType.Object({ id: Type.Number() })Your stack speaks JSON Schema (Fastify, OpenAPI, Ajv) and you want TypeScript types from the same object.
JSON Schema{"type": "object", "required": ["id"]}The contract must be language-neutral: API docs, validators in Python, Go or Java, or form generators.

An interface disappears at compile time. It does not check the object your fetch call returns. If a wrong shape from the server would be a real problem, generate a schema and parse data where it enters your app.

Generate TypeScript types + runtime validation together

Writing an interface and a validator by hand means keeping two definitions in step, and they drift. In Zod, Valibot and TypeBox mode the Types + runtime validation switch (on by default) emits each schema followed by the type inferred from it, so there is a single source of truth. Turn it off if you only want the schemas. For this input:

[
  { "id": 7, "email": "ada@example.com", "nickname": null, "address": { "city": "London" } },
  { "id": 8, "email": "alan@example.com", "nickname": "al" }
]

with the root name Users, the three libraries produce the same shape. nickname is nullable because one item had null, and address is optional because one item lacked it:

// Zod
import { z } from "zod";

export const AddressSchema = z.object({
  city: z.string(),
});
export type Address = z.infer<typeof AddressSchema>;

export const UserSchema = z.object({
  id: z.number(),
  email: z.string(),
  nickname: z.string().nullable(),
  address: AddressSchema.optional(),
});
export type User = z.infer<typeof UserSchema>;

export const UsersSchema = z.array(UserSchema);
export type Users = z.infer<typeof UsersSchema>;
// Valibot (AddressSchema and UsersSchema follow the same pattern)
import * as v from "valibot";

export const UserSchema = v.object({
  id: v.number(),
  email: v.string(),
  nickname: v.nullable(v.string()),
  address: v.optional(AddressSchema),
});
export type User = v.InferOutput<typeof UserSchema>;
// TypeBox (AddressSchema and UsersSchema follow the same pattern)
import { Type, type Static } from "@sinclair/typebox";

export const UserSchema = Type.Object({
  id: Type.Number(),
  email: Type.String(),
  nickname: Type.Union([Type.String(), Type.Null()]),
  address: Type.Optional(AddressSchema),
});
export type User = Static<typeof UserSchema>;

Nested schemas are declared before the schemas that use them, so the file runs top to bottom without hoisting problems.

Zod vs Valibot vs TypeBox

All three let you validate unknown data and get a TypeScript type from the same definition. They differ in API style and in what the schema object is.

ZodValibotTypeBox
API styleChained methods: z.string().nullable()Standalone functions: v.nullable(v.string())Builders: Type.Union([Type.String(), Type.Null()])
ValidateSchema.parse(data), Schema.safeParse(data)v.parse(Schema, data), v.safeParse(Schema, data)Value.Check(Schema, data), or TypeCompiler.Compile(Schema)
Inferred typez.infer<typeof S>v.InferOutput<typeof S>Static<typeof S>
Bundle sizeMethods live on schema objects, so most of the library ships even if you use a little of it. Zod 4 adds a lighter zod/mini entry point with a functional API.Built to be tree-shaken: each validator is a separate function, so you ship only what you import. Usually the smallest in a browser bundle.Schemas are plain JSON Schema objects. The checker (Value) and compiler are separate imports, and it is most often used server-side.
JSON SchemaExportable with z.toJSONSchema() in Zod 4Exportable with @valibot/to-json-schemaNative: the schema object is JSON Schema, so Ajv can use it directly
Good fittRPC, React Hook Form, most form and API libraries; teams that want the most examplesFront-end apps, edge functions, anywhere bundle size mattersFastify, OpenAPI, services already standardised on JSON Schema, high-throughput validation

Using the generated schema

// Zod: parse throws a ZodError; safeParse returns { success, data | error }
const users = UsersSchema.parse(await res.json());
const r = UsersSchema.safeParse(json);
if (!r.success) console.error(r.error.issues);
// Valibot: parse throws a ValiError; safeParse returns { success, output, issues }
import * as v from "valibot";
const users = v.parse(UsersSchema, await res.json());
const r = v.safeParse(UsersSchema, json);
if (!r.success) console.error(r.issues);
// TypeBox: Value.Check narrows the type; Value.Errors explains failures
import { Value } from "@sinclair/typebox/value";
import { TypeCompiler } from "@sinclair/typebox/compiler";

if (!Value.Check(UsersSchema, json)) console.error([...Value.Errors(UsersSchema, json)]);

const UsersCheck = TypeCompiler.Compile(UsersSchema);   // compile once, check many times
if (UsersCheck.Check(json)) {
  json;   // typed as Users here
}

JSON Schema output

Choose JSON Schema to get a draft 2020-12 document from the same inference. The root shape sits at the top level, each nested object goes in $defs and is referenced with $ref, every object lists its required keys, and null unions use type arrays:

[{"sku": "A-1", "note": null}, {"sku": "A-2", "note": "gift", "qty": 2}]

// generated (root name: Lines)
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Lines",
  "type": "array",
  "items": { "$ref": "#/$defs/Line" },
  "$defs": {
    "Line": {
      "type": "object",
      "properties": {
        "sku":  { "type": "string" },
        "note": { "type": ["string", "null"] },
        "qty":  { "type": "integer" }
      },
      "required": ["sku", "note"]
    }
  }
}

Test the schema against more payloads in the JSON Schema validator. For options such as formats, enums and additionalProperties, use the dedicated JSON to JSON Schema generator.

JSON to TypeScript POJO and class generator

If you want model classes rather than type-only interfaces — a “POJO” (plain old JavaScript object) model, a DTO for a NestJS controller, or an entity you will decorate for TypeORM — choose Class. Every object in the sample becomes an exported class, nested objects get their own classes named from their keys, arrays become typed arrays, keys that are not valid identifiers are quoted, and fields missing from some array items are marked optional with ?.

{"id": 1, "tags": ["a"], "owner": {"name": "Ada"}}

// generated with Class
export class Root {
  id!: number;
  tags!: string[];
  owner!: Owner;
}

export class Owner {
  name!: string;
}

The ! is TypeScript’s definite-assignment assertion: it tells tsc --strict the field will be filled (for example by Object.assign(new Root(), json) or class-transformer’s plainToInstance) so the class compiles without a constructor. A value that is only ever null in the sample is typed null; widen it by hand (for example to string | null) once you know the real type. Need models for another language? See the JSON to Go, JSON to Python and JSON to Java converters.

Getting accurate types from a sample

Other ways to generate types

# quicktype: several samples, many languages, JSON Schema input
npx quicktype -l ts -s json -o types.ts sample1.json sample2.json

# from an OpenAPI spec instead of a sample
npx openapi-typescript openapi.yaml -o api-types.ts

If your API has an OpenAPI or JSON Schema definition, generating types from that is more reliable than inferring them from a sample. Use this converter when all you have is real data.

Frequently asked questions

How do I convert JSON to TS?

Paste a JSON object or array into the input box and the TypeScript appears on the right as you type. Pick Interface, Type, Class, Zod, Valibot, TypeBox or JSON Schema in the output toggle, set the root name, then copy the result or download it as a file.

Why is a field marked optional?

A field gets ? (or .optional(), v.optional, Type.Optional, or is left out of required) only when the input is an array of objects and the field is present in some items but missing from others. A single object never produces optional fields unless you turn on null → optional, which also marks fields that were null.

Should I use interface or type in TypeScript?

For plain object shapes they are equivalent. Interfaces can be extended and declaration-merged and are the usual default. Type aliases are needed for unions and mapped types. Pick one style for your codebase, and the generator follows it for every nested type.

Can it generate a TypeScript POJO or class from JSON?

Yes. Choose Class to get a plain TypeScript class, a POJO-style model, for the root object and one for every nested object. Required fields use the definite-assignment ! so the classes compile under strict mode, optional fields get ?, and you can add decorators from class-validator, TypeORM or NestJS on top.

Can it generate Zod, Valibot or TypeBox schemas from JSON?

Yes. Choose Zod, Valibot or TypeBox. You get one object schema per nested shape, with optional and nullable wrappers where the sample needs them. With Types + runtime validation switched on (the default), every schema is followed by its inferred type: z.infer, v.InferOutput or Static, so the runtime check and the static type come from one definition.

Which should I use: Zod, Valibot or TypeBox?

Zod has the largest ecosystem and a familiar chained API. Valibot uses small standalone functions so bundlers can drop what you do not import, which suits browser and edge code. TypeBox builds standard JSON Schema objects, so it fits Fastify, OpenAPI and Ajv-based stacks. The generated shapes are equivalent, so you can switch later.

Can it output a JSON Schema?

Yes. Choose JSON Schema to get a draft 2020-12 schema with a required list for every object, nested objects in $defs referenced with $ref, null unions as type arrays such as ["string", "null"], and integer instead of number when every sample value was a whole number.

Can I paste a JavaScript object or broken JSON?

Yes. Unquoted keys, single quotes, trailing commas, comments, Python True/False/None and missing commas are repaired before the types are inferred, and the tool lists every fix it made. Integers larger than 2^53 are kept exact while parsing and flagged, because they lose precision as a JavaScript number.

Is my JSON sent to a server?

No. Parsing and type generation run in JavaScript in your browser, so you can safely paste internal API responses.