Convert Simple JSON to a Python Dataclass
Learn how to convert a flat JSON object into a Python dataclass with properly typed fields. Covers str, int, float, and bool type annotations.
Detailed Explanation
From JSON to a Python Dataclass
The simplest conversion turns a flat JSON object into a Python @dataclass. Each JSON key becomes a field with a type annotation inferred from the value.
Example JSON
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"active": true,
"score": 98.5
}
Generated Python
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str
active: bool
score: float
Type Mapping Rules
| JSON type | Python type |
|---|---|
| string | str |
| number (integer) | int |
| number (decimal) | float |
| boolean | bool |
| null | None |
Python distinguishes between int and float, so 42 maps to int while 98.5 maps to float. This is more precise than languages like TypeScript that use a single number type.
Why Dataclasses?
Dataclasses (introduced in Python 3.7) provide:
- Auto-generated
__init__— No boilerplate constructor needed. __repr__and__eq__— Useful for debugging and testing.- Type annotations — IDE autocompletion and static analysis with mypy or pyright.
- Immutability option — Set
frozen=Trueto prevent accidental mutation.
Usage
import json
data = json.loads('{"id": 42, "name": "Alice", "email": "alice@example.com", "active": true, "score": 98.5}')
user = User(**data)
print(user.name) # "Alice"
A simple dataclass is the foundation for all JSON-to-Python conversions. Once you understand this pattern, nested objects, optional fields, and complex structures follow naturally.
Use Case
You receive a JSON payload from a REST API and want a type-safe Python class that gives you IDE autocompletion, catches typos with mypy, and provides a clean __repr__ for debugging.
Try It — JSON to Python Converter
Related Topics
Convert Nested JSON Objects to Python Dataclasses
Dataclasses
Handle Optional and Nullable JSON Fields in Python
Type Annotations
Convert JSON Arrays to Python List Type Annotations
Type Annotations
Python Dataclass Fields with Default Values from JSON
Dataclasses
Create Immutable Python Dataclasses from JSON
Dataclasses