JSON to Python Dataclass
Paste a JSON sample and get a @dataclass (or Pydantic BaseModel) with type hints for every field, str, int, float, bool, Optional[...] and List[...] where appropriate. Nested objects become their own dataclasses. Output is PEP 8-formatted and ready to paste into a Python file.
How to convert JSON to a dataclass
-
1
Paste the JSON
A single sample works; multiple samples improve nullability detection.
-
2
Pick the style
Standard library `@dataclass`, Pydantic `BaseModel`, or `TypedDict` for static type-checking only.
-
3
Pick Python version
3.9+ for `list[str]` syntax, 3.10+ for `|` union types, 3.8 for `Optional[...]` / `List[...]`.
-
4
Copy the code
One root class plus nested ones. Paste into a `.py` file and import.
Example output: standard @dataclass
Input:
{ "first_name": "Alice", "age": 30, "email": null, "tags": ["admin"] }
Output (Python 3.10+):
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class User:
first_name: str
age: int
tags: list[str] = field(default_factory=list)
email: Optional[str] = None
Same input with Pydantic
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
first_name: str
age: int
email: Optional[str] = None
tags: list[str] = []
Type mapping
| JSON value | Python type |
|---|---|
| string | str |
| integer | int |
| number (decimal) | float |
| boolean | bool |
| null (seen alone) | None |
| null + other type | Optional[T] |
| ISO date string | date (Python 3.7+) |
| ISO datetime | datetime |
| array of one type | list[T] |
| mixed array | list[Union[T1, T2]] |
| object | Nested class |
Dataclass vs Pydantic vs TypedDict
| Flavour | When to use |
|---|---|
@dataclass |
Standard-library solution, no runtime validation |
| Pydantic | Runtime validation and coercion (FastAPI, settings) |
TypedDict |
Static type checking only, no instance class |
attrs |
Legacy projects that standardized on attrs |
Common mistakes
- Forgetting
default_factoryfor mutable defaults. Alist[str] = []default is a dataclass trap (shared across instances). Usefield(default_factory=list). - Optional without default.
email: Optional[str]without= Nonestill requires the argument. Match your JSON semantics. - Pydantic v1 vs v2. Syntax and behaviours differ (class
Configvsmodel_config,validatorvsfield_validator). The generator defaults to v2. - Union order matters for deserialization. Pydantic tries types in declaration order. Put the most specific first (e.g.
intbeforestr) if ambiguity is possible.
Frequently Asked Questions
Dataclass for simple value holders with no validation. Pydantic when you want runtime validation, coercion, or FastAPI integration. TypedDict when you only need static type checking (mypy, pyright) and do not want class instances.
Not for Python 3.10+ where | unions and list[str] syntax are native. Useful for 3.7-3.9 projects to use the newer syntax via PEP 563 string annotations. The generator warns when it’s needed.
Each nested object becomes its own class. The root class references them by name, so you can reuse types. Circular references are detected and flagged.
Yes, if you pick the Pydantic flavour. FastAPI uses Pydantic models as request/response types directly. For internal data shuffling, @dataclass is lighter-weight.
Related Tools
ASCII Table Reference
Full ASCII table from 0 to 127 with decimal, hex, octal, binary, standard names and HTML numeric-reference notation, including NUL, LF and DEL.
Color Palette Generator
Generate monochromatic, analogous, complementary, triadic or tetradic color palettes from a base HEX color and export copy-ready CSS variables.
HTML Character Reference
Searchable list of HTML entities, their named and numeric codes, and a one-click copy for special characters and symbols.
FPS Counter
Measure browser FPS with requestAnimationFrame, smoothing, min/max frame rate, warnings and an optional graph. Runs locally with no upload or API.
HEX Color Picker
Pick or enter a HEX colour and get RGB, HSL, approximate CMYK, relative luminance and contrast ratios against white and black.
JSON Formatter
Paste JSON to pretty-print with 2 or 4 spaces, minify it to compact output, or run a quick syntax check before copying the result.
Tool available in other languages
- JSON zu Python Dataclass [DE]
- JSON ke Dataclass Python [ID]
- JSON에서 Python 데이터 클래스로 변환하기 [KO]
- Từ JSON đến lớp dữ liệu Python [VI]
- JSON till Python-dataklass [SV]
- JSON naar Python-dataclass [NL]
- JSON a Dataclass de Python [ES]
- JSON vers Dataclass Python [FR]
- JSONからPythonデータクラスへの変換 [JA]
- JSON do klasy danych w Pythonie [PL]
- JSON ถึงคลาสข้อมูลใน Python [TH]
- فئة بيانات من JSON إلى بايثون [AR]
- JSON para Dataclass em Python [PT]
- 从 JSON 到 Python 数据类 [ZH]
- JSON in Dataclass Python [IT]
- JSON в класс данных для Python [RU]
- JSON'dan Python Veri Sınıfına [TR]