DevToolBox

JSON to TypeScript Converter

ブラウザ内で処理

JSONデータからTypeScript・Go・Rust・Python (Pydantic)・Zodの型やスキーマを自動生成します。

結果

// ここに結果が表示されます

How to Use the JSON to TypeScript Converter

This tool generates TypeScript, Go, Rust, Python Pydantic, or Zod definitions from JSON data. Paste your JSON and choose an output language to get code instantly. Nested objects are extracted into separate interfaces, array element types are inferred, and property names with special characters are properly quoted. Perfect for quickly typing API responses in TypeScript projects. All processing happens in your browser.

Features

  • Generate TypeScript, Go structs, Rust serde types, Python Pydantic models, or Zod schemas
  • Nested objects become separate, named interfaces instead of one deep inline type
  • Array element types are inferred; mixed primitives produce a union like (string | number)[]
  • Keys that are not valid identifiers (user-id, 2fa) are automatically quoted
  • Switch between interface and type alias output with one checkbox
  • Custom root name, so the generated type drops straight into your codebase

Interface vs. Type Alias

For plain object shapes the two are interchangeable. Choose interface if you plan to extend the shape with extends or rely on declaration merging; choosetype if the result will be combined into unions or mapped types. This tool generates identical members either way, so you can switch later with a one-line edit.

How Type Inference Works

The converter inspects strings, numbers, booleans and null, merges all array elements, and lifts nested objects into named definitions. Keys missing from some array objects become optional. JSON dates remain strings and should be reviewed by hand.

JSON to TypeScript Converterの使い方

JSONデータを貼り付けて「変換」ボタンを押すと、TypeScriptのinterface定義が自動生成されます。 ネストされたオブジェクトは個別のinterfaceとして抽出され、配列の要素型も自動推論します。 ルート名は自由に変更でき、「type (interfaceの代わり)」にチェックを入れると type エイリアス形式で出力されます。 API開発でレスポンスの型定義を素早く作成するのに便利です。 TypeScript・Go・Rust・Python (Pydantic v2)・Zod の5形式を選べます。

図1: ネストしたオブジェクトが別interfaceになり、混在配列がユニオン型になる仕組み
JSONからTypeScript型を生成する仕組みJSONのaddressプロパティのようなネストしたオブジェクトはプロパティ名を使った別のinterface Addressとして抽出され、文字列と数値が混在するtags配列はunion型(string | number)[]として推論されることを示す図入力JSON{id: 1,address: {city: "Tokyo"},tags: ["a", 1]}生成されるTypeScriptinterface Root {id: number;address: Address;tags: (string | number)[];}interface Address {city: string;}別interfaceとして抽出混在配列→union型

1. APIレスポンスの型付け

fetch で取得したレスポンスをそのまま貼り付け、生成された interface をtypes.ts に保存するのが最短の使い方です。as any でキャストする代わりにconst user: User = await res.json() と型注釈を付ければ、フィールド名のタイポを コンパイル時に検出できます。レスポンスが整形されていない場合は先にJSON Formatterで構文エラーがないか確認すると安全です。

2. Webhookペイロードの型化

Stripe や GitHub などの Webhook はペイロードが大きく、手書きで型を起こすと漏れが出がちです。 テスト送信で受け取った実ペイロードを貼り付ければ、ネストの深いオブジェクトも一括で interface 化されます。 ドキュメントに載っていないフィールドが実際には飛んできている、といった差異の発見にも役立ちます。

3. バックエンド完成前のフロント先行開発

API 仕様書のサンプル JSON から型を生成しておけば、バックエンドの実装を待たずに フロントエンドのコンポーネント開発を進められます。後で実レスポンスと食い違いがないかはJSON Diffでサンプルと実データを比較すると確認しやすくなります。

型推論が外れるnull・配列の落とし穴 / Where Type Inference Fails on null and Arrays

JSONからの型推論は「そのサンプルに写っている形」しか分かりません。自動生成した型をそのまま信用すると 実行時エラーの原因になる典型パターンをまとめました。

Type inference only sees the shape of the sample you paste. These are the patterns where the generated types need a manual review.

落とし穴 / Pitfall原因 / Cause対処 / Fix
nullのフィールドがnull型になる
A null field is typed as null
サンプル値がたまたまnullだと本来の型が分からない
When the sample happens to be null, the real type is unknowable
実際の型に手で広げる(例: string | null)
Widen by hand, e.g. string | null
オプショナル?が付かない
Optional properties are never detected
JSONには「省略されうる」という情報が存在しない
JSON carries no optionality information
複数サンプルを比較し、欠けるキーに?を手動付与
Compare multiple samples and add ? manually
配列内のオブジェクト形状が混在すると最後の要素で上書き
Mixed object shapes in an array: the last element wins
要素ごとに同名interfaceを生成するため前の形状が消える
Each element generates the same interface name, overwriting earlier shapes
全フィールドを含む代表要素で変換するか、手動でユニオン化
Convert from a representative element, or build the union by hand
ルートが配列だと先頭要素しか見ない
For a root-level array, only the first element is inspected
パフォーマンスと曖昧さ回避のため先頭要素のみ走査する仕様
By design, only parsed[0] is walked
全キーを持つ要素を先頭に置いてから変換
Move an element containing every key to the front first
日付がstringになる
Dates come out as string
JSONに日付型はなくISO 8601も単なる文字列
JSON has no date type; ISO 8601 is just a string
型はstringのまま、受信後にnew Date()で変換
Keep string and convert with new Date() after parsing
動的キーが個別プロパティに展開される
Dynamic keys are expanded into individual properties
IDをキーにした連想配列か固定キーかは機械判別できない
A map keyed by IDs is indistinguishable from fixed keys
Record<string, T>やインデックスシグネチャに書き換え
Rewrite as Record<string, T> or an index signature
空配列がunknown[]になる
Empty arrays become unknown[]
要素が無いため型を推論できない
There is no element to infer from
API仕様から実型を補う(例: string[])
Fill in the real type from the API spec, e.g. string[]

quicktypeの型生成とZod検証 / Type generation with quicktype and validation with Zod

JSONからの型生成をCIやスクリプトで自動化する場合の最小サンプル。

Minimal snippets to generate TypeScript types from JSON in scripts and CI.

Shell (quicktype CLI)

# JSONファイルからTypeScript型を生成 / Generate TS types from a JSON file
npx quicktype --lang ts --just-types --top-level User user.json -o user.ts

# APIレスポンスから直接 / Straight from an API response
curl -s https://api.example.com/user | npx quicktype --lang ts --just-types --top-level User -o user.ts

JavaScript / TypeScript (quicktype-core)

import { quicktype, InputData, jsonInputForTargetLanguage } from "quicktype-core";

const jsonInput = jsonInputForTargetLanguage("typescript");
await jsonInput.addSource({ name: "User", samples: [jsonString] });

const inputData = new InputData();
inputData.addInput(jsonInput);

const { lines } = await quicktype({
  inputData,
  lang: "typescript",
  rendererOptions: { "just-types": "true" },
});
console.log(lines.join("\n"));

Python (Pydantic v2)

Select Python (Pydantic) to generate BaseModel classes, with child models before their parents and Field aliases for renamed keys.

TypeScript (Zod runtime validation)

Select Zod to generate a schema and its inferred TypeScript type.

import { z } from "zod";

export const Root = z.object({
  id: z.number().int(),
  name: z.string(),
  tags: z.array(z.string()),
});

export type Root = z.infer<typeof Root>;

ネスト・null・特殊キーの型変換 / Typing nested JSON, nulls, and special keys

例1: ネストされたJSONをinterfaceに分割 / Nested JSON into separate interfaces

{
  "id": 1,
  "name": "Aoi",
  "address": { "city": "Tokyo", "zipCode": "100-0001" }
}

↓

interface Address {
  city: string;
  zipCode: string;
}

interface Root {
  id: number;
  name: string;
  address: Address;
}

例2: null・混在配列は生成後に手直し / Review null and mixed arrays

{ "nickname": null, "scores": [80, "N/A", 92] }

↓ 自動生成 / generated

interface Root {
  nickname: null;
  scores: (number | string)[];
}

↓ 手直し後 / after manual fix

interface Root {
  nickname: string | null;
  scores: (number | "N/A")[];
}

例3: 識別子に使えないキーは自動クォート / Invalid identifiers are quoted

{ "user-id": 42, "2fa": true }

↓ typeモード / type alias mode

type Root = {
  "user-id": number;
  "2fa": boolean;
};

ハイフン入り・数字始まりのキーはクォート必須。ドット記法ではなく obj["user-id"] でアクセスします。

Keys with hyphens or leading digits must stay quoted; access them with bracket notation.

APIレスポンスを送信せず型生成 / Generate types without uploading API responses

The JSON you paste into a type generator is rarely a toy example — it is usually a real API response captured from staging or production, complete with bearer tokens, session IDs, email addresses, and internal record identifiers. Sending that payload to a server-side converter means handing your live data to a third party just to get a type definition back. DevToolBox performs the entire conversion — JSON.parse, recursive type inference, and interface generation — inside your browser with no network request at all. You can verify this yourself: open DevTools, switch to the Network tab, run a conversion, and watch the tab stay empty. The page also works offline once loaded. For typing confidential payloads from internal systems, that guarantee matters more than any feature.

型生成に貼り付けるJSONは、検証環境や本番から取得した「生のレスポンス」であることがほとんどで、 アクセストークンやメールアドレス、社内IDが含まれがちです。本ツールはパースから型推論・interface生成まで すべてブラウザ内で完結し、ネットワーク送信は一切行いません。DevTools の Network タブが空のままであることで 確認でき、一度読み込めばオフラインでも動作します。

🔒 すべての処理はブラウザ内で完結し、入力データはサーバーへ送信されません。登録不要・無料。 / All processing runs in your browser; nothing is uploaded. Free, no sign-up. プライバシーポリシー / Privacy Policy

参考資料 / References

関連ガイド / Related Guides