Generate Typed Code from JSON — TypeScript, Python, Go, Rust & More
Convert JSON to typed code in 8 programming languages. See how type inference works, with before-and-after examples for TypeScript interfaces, Python dataclasses, Go structs, Rust serde, and more.
Why Generate Code from JSON?
Every project that consumes a JSON API eventually needs typed models. You copy a sample response into your editor, eyeball the fields, and start writing an interface or struct by hand. It works — until the payload has 40 fields, three levels of nesting, and an array of polymorphic objects. Then it's tedious, error-prone, and slow.
A code generator eliminates that manual step. Paste a JSON sample, pick a language, and get production-ready type definitions in seconds. The benefits are concrete:
- Time savings — generating types for a 50-field payload takes seconds instead of minutes.
- Type safety — your compiler or runtime catches mismatches before they reach production.
- Less boilerplate — no more hand-writing getters, setters, JSON tags, or serde annotations.
- Consistency — every team member gets the same models from the same source data.
How Type Inference Works
A JSON-to-code generator reads your sample data and infers a type for each value. Strings become string, numbers become int or float depending on the presence of a decimal point, booleans map directly, and null produces an optional/nullable wrapper. Objects become named types (structs, classes, interfaces), and arrays become typed collections of whatever their elements are.
Here's how JSON types map across languages:
| JSON Type | TypeScript | Python | Java | Go | Rust | Swift |
|---|---|---|---|---|---|---|
| string | string | str | String | string | String | String |
| number (int) | number | int | int | int64 | i64 | Int |
| number (float) | number | float | double | float64 | f64 | Double |
| boolean | boolean | bool | boolean | bool | bool | Bool |
| null | null | None | null | *T (pointer) | Option<T> | T? |
| object | interface | dataclass | class (POJO) | struct | struct | struct (Codable) |
| array | T[] | list[T] | List<T> | []T | Vec<T> | [T] |
The key insight: a generator only knows what it sees. If your sample data has 42 for a field that can also be 42.5, the generator will pick int instead of float. Use representative sample data for accurate types.
Sample Input
We'll use this JSON throughout the examples below. It covers strings, numbers, booleans, a nested object, and an array:
{
"id": 1,
"name": "Alice Johnson",
"email": "alice@example.com",
"active": true,
"score": 97.5,
"address": {
"street": "123 Main St",
"city": "Portland",
"zip": "97201"
},
"tags": ["admin", "editor"]
}TypeScript Interfaces from JSON
TypeScript is the most common target. The generator creates an interface for each object, using the field names as property keys:
interface Address {
street: string;
city: string;
zip: string;
}
interface Root {
id: number;
name: string;
email: string;
active: boolean;
score: number;
address: Address;
tags: string[];
}Every field is typed, the nested address object gets its own interface, and tags is inferred as string[] from its contents. You can paste this directly into your project and start using it with full autocomplete and compile-time checks.
Python Dataclasses from JSON
Python's @dataclass decorator generates __init__, __repr__, and comparison methods automatically. Combined with type hints, it's the cleanest way to define JSON models in Python:
from dataclasses import dataclass
@dataclass
class Address:
street: str
city: str
zip: str
@dataclass
class Root:
id: int
name: str
email: str
active: bool
score: float
address: Address
tags: list[str]Pair this with a library like dacite or cattrs to deserialize JSON dictionaries directly into these dataclass instances.
Java POJOs from JSON
Java requires more ceremony — fields, a constructor, and getters/setters. A generator saves the most time here:
public class Address {
private String street;
private String city;
private String zip;
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getZip() { return zip; }
public void setZip(String zip) { this.zip = zip; }
}
public class Root {
private int id;
private String name;
private String email;
private boolean active;
private double score;
private Address address;
private List<String> tags;
// getters and setters...
}The generated POJOs work directly with Jackson, Gson, or any other JSON serialization library in the Java ecosystem.
Go Structs from JSON
Go structs use field tags to control JSON marshaling. The generator produces idiomatic Go with exported fields and json:"..." tags:
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Zip string `json:"zip"`
}
type Root struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
Score float64 `json:"score"`
Address Address `json:"address"`
Tags []string `json:"tags"`
}The tags ensure json.Unmarshal maps lowercase JSON keys to exported (uppercase) Go fields. Field names are automatically PascalCased, and id becomes ID following Go naming conventions.
Rust Structs from JSON
Rust uses the serde crate for serialization. The generator adds the necessary derive macros:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Address {
pub street: String,
pub city: String,
pub zip: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
pub id: i64,
pub name: String,
pub email: String,
pub active: bool,
pub score: f64,
pub address: Address,
pub tags: Vec<String>,
}With serde_json, you can deserialize a JSON string into these structs with a single call to serde_json::from_str. The compiler enforces every field is present and correctly typed.
Swift Codable from JSON
Swift's Codable protocol enables built-in JSON encoding and decoding with zero external dependencies:
struct Address: Codable {
let street: String
let city: String
let zip: String
}
struct Root: Codable {
let id: Int
let name: String
let email: String
let active: Bool
let score: Double
let address: Address
let tags: [String]
}Use JSONDecoder().decode(Root.self, from: data) to parse JSON data directly into these structs. Swift infers the coding keys from property names automatically.
Handling Nested Objects and Arrays
Nested objects are the most interesting part of code generation. When the generator encounters an object value inside another object, it creates a separate named type. The naming convention is typically based on the field name:
- A field named
addresscontaining an object produces a type calledAddress. - A field named
shipping_detailsproducesShippingDetails(PascalCased). - Deeply nested objects follow the same pattern recursively — an
addresswith a nestedcoordinatesobject produces bothAddressandCoordinatestypes.
Arrays of objects are handled similarly. If items is an array of objects, the generator examines the first element (or merges all elements) to infer the type, and creates a singular-named type like Item.
Arrays of primitives (["admin", "editor"]) are straightforward — they become string[], Vec<String>, []string, etc. depending on the target language.
Tips for Better Generated Code
The quality of generated types depends entirely on the quality of your input data. A few practical tips:
- Use representative sample data. Include at least one example of every field variation. If a field can be
null, include a null value so the generator marks it as optional. - Keep types consistent. If
idis a number in some records and a string in others, the generator has to pick one or use a union type. Clean your sample data first. - Rename the root type. Most generators default to
Rootas the top-level name. Rename it to something meaningful likeUserorApiResponseafter generating. - Flatten before generating if you only need a subset of the structure. Trim your JSON sample to just the fields you care about.
- Check edge cases. Empty arrays (
[]) can't be typed without context. Populate them with at least one element so the generator knows the item type. - Review and adjust. Generated code is a starting point. You may want to rename fields, adjust integer widths, add validation annotations, or mark optional fields based on your domain knowledge.
Try It Yourself
Generate typed code instantly: Paste any JSON into our JSON to Code generator and get production-ready types for TypeScript, Python, Java, Go, Rust, Swift, Kotlin, and C#. No sign-up required.