JSON to Python: Dataclasses You Can Fill with json.loads
json.loads gives you nested dicts and lists. Paste a real sample here and get typed dataclasses plus the small bit of code that turns those dicts into objects and back.
Paste or upload your JSON
Use JSON your code really receives, such as an API response or a config file. A field that never shows up in the sample can't show up in the classes, so a fuller sample gives better types.
Example input
{
"user": {
"id": 12345,
"name": "Priya Sharma",
"email": "[email protected]",
"age": 29,
"is_premium": true,
"skills": [
"Python",
"Machine Learning",
"Data Science"
],
"address": {
"street": "123 Tech Street",
"city": "Mumbai",
"country": "India",
"postal_code": "400001"
}
}
}Let the types come from your data
The output follows your data, so a quick look at the type hints tells you whether the sample was a good one.
Read the generated dataclasses
This is the full output for the example above. The keys were already snake_case, so the field names match them one to one.
Output for the example above
# Python 3.7+ dataclasses that need only the standard library. Read your JSON with:
# import json
# data = Root.from_dict(json.loads(text))
# and write it back with json.dumps(data.to_dict()).
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, List
@dataclass
class Root:
user: User
@classmethod
def from_dict(cls, obj: Dict[str, Any]) -> "Root":
return cls(
user=User.from_dict(obj["user"]),
)
def to_dict(self) -> Dict[str, Any]:
return {
"user": self.user.to_dict(),
}
@dataclass
class User:
id: int
name: str
email: str
age: int
is_premium: bool
skills: List[str]
address: Address
@classmethod
def from_dict(cls, obj: Dict[str, Any]) -> "User":
return cls(
id=obj["id"],
name=obj["name"],
email=obj["email"],
age=obj["age"],
is_premium=obj["is_premium"],
skills=obj["skills"],
address=Address.from_dict(obj["address"]),
)
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"name": self.name,
"email": self.email,
"age": self.age,
"is_premium": self.is_premium,
"skills": self.skills,
"address": self.address.to_dict(),
}
@dataclass
class Address:
street: str
city: str
country: str
postal_code: str
@classmethod
def from_dict(cls, obj: Dict[str, Any]) -> "Address":
return cls(
street=obj["street"],
city=obj["city"],
country=obj["country"],
postal_code=obj["postal_code"],
)
def to_dict(self) -> Dict[str, Any]:
return {
"street": self.street,
"city": self.city,
"country": self.country,
"postal_code": self.postal_code,
}Copy or download the .py file
Save the file next to the code that calls your API and load the response with the line from the top comment. The classes also work with mypy and IDE autocompletion, since every field has a type hint.
What is JSON to Python Conversion?
In Python, json.loads already turns JSON into dicts and lists, so nothing stops you from writing data["user"]["address"]["city"] everywhere. It works until a key is misspelled or a field turns out to be missing. Dataclasses give the same data names your editor can complete and types a checker like mypy can verify.
This page writes those classes from a real sample. If your data is XML, the XML to Python page does the same job, and Python to JSON goes the other way.
Frequently Asked Questions
What does the generated code need to run?
Python 3.7 or newer and nothing else. The file imports dataclasses and typing from the standard library and starts with from __future__ import annotations, so classes can refer to each other in any order. There is no pydantic, marshmallow or other package involved; each class has a small from_dict() and to_dict() written out in plain Python.
How do I load my JSON into these classes?
Parse the text with json.loads (or json.load for a file) and pass the result to Root.from_dict. The comment at the top of the output shows the exact line, including the list comprehension you need when your JSON is an array. to_dict() goes the other way, so json.dumps(data.to_dict()) gives you JSON with the original keys again.
How are int and float chosen, and what happens to long IDs?
The page looks at how each number is written in your JSON, across every item of a list. Whole numbers become int, and because Python ints have no size limit, an ID like 8901240544102066246 keeps every digit when json.loads reads it. Numbers written with a decimal point or exponent, such as 14.50 or 1e3, become float; if a field mixes whole numbers and decimals it is float too. Quoted values like "00501" stay str. One thing to know: json.loads turns 14.50 into the float 14.5, so if the exact decimal matters, call json.loads(text, parse_float=decimal.Decimal).
Why are some fields Optional with = None?
A field becomes Optional when it is null somewhere in your JSON or missing from some items of a list, and from_dict reads it with obj.get() so a missing key is fine. Every other field is required and read with obj["key"], which raises KeyError if a later response leaves it out. Dataclasses need fields without a default first, so the Optional ones are listed after the required ones; from_dict and to_dict use keyword names, so the order never matters.
How are odd JSON keys turned into Python names?
Keys are split into words and joined in snake_case, so planId becomes plan_id. Python keywords get a trailing underscore (class becomes class_, from becomes from_), keys that start with a digit get a field_ prefix, and names that collide, like first-name and firstName, get a number. Class names that would hide List, Dict, Optional or a built-in exception get Model added. The original key is always kept in from_dict and to_dict.
Is my JSON sent anywhere?
No. The dataclasses are generated in your browser as you type, and nothing you paste or upload is sent to our server or kept after you leave the page.
Related Tools
JSON to C
Convert JSON data to C structs with parsing functions and memory management
JSON to C++
Convert JSON data to modern C++ classes with STL containers and smart pointers
JSON to C#
Convert JSON data to C# classes with properties and attributes
JSON to Java
Convert JSON data to Java classes with getters, setters, and annotations
JSON to TypeScript
Convert JSON data to TypeScript interfaces and types
JSON to TS
Generate TS (TypeScript) type definitions from JSON data