JSON to Python Converter — dataclass, Pydantic, TypedDict
Convert JSON to Python dataclasses, Pydantic models, or TypedDict. Auto-infers types with Optional support.
How to Use
- Paste your JSON data into the left panel.
- Select the output mode: dataclass, Pydantic v2, or TypedDict.
- Optionally change the class name and toggle Optional or future annotations.
- Python code is generated automatically as you type — no button click needed.
- Copy the output and paste it into your Python project.
Why Convert JSON to Python Types?
Working with raw dictionaries in Python leads to bugs that are hard to catch. A typo in a key name, an unexpected None, or a missing field can crash your program at runtime with an unhelpful KeyError. By converting your JSON into typed Python classes, you get autocompletion in your editor, static type checking with mypy or Pyright, and clear documentation of your data's shape.
This tool automates what would otherwise be tedious manual work: analyzing JSON structure, inferring types for each field, handling nested objects, and writing out the class definitions with correct type annotations. It supports all three major approaches to structured data in Python.
Python Dataclasses
Introduced in Python 3.7, dataclasses are the standard library solution for structured data. The @dataclass decorator auto-generates __init__, __repr__, __eq__, and optionally __hash__ methods. They're lightweight, require no external dependencies, and integrate seamlessly with type checkers.
Dataclasses are ideal when you control the data creation and don't need runtime validation. They work well for internal data models, configuration objects, and domain entities. If you enable frozen=True, you can make instances immutable. The field() function provides default factories for mutable defaults like lists and dicts.
Pydantic v2 Models
Pydantic is the most popular data validation library in Python, used by FastAPI, LangChain, and thousands of other projects. Pydantic v2, rewritten with a Rust core, is dramatically faster than v1 — up to 5-50x faster validation depending on the data structure.
Unlike dataclasses, Pydantic models validate data at runtime. Pass a dictionary to a model's constructor and Pydantic will parse it, coerce types where possible (e.g., the string "42" becomes integer 42), and raise detailed ValidationError exceptions on invalid input. This makes Pydantic the right choice for API request/response handling, config file parsing, and any scenario where data arrives from an untrusted external source.
Pydantic v2 models also support serialization to dict and JSON, custom validators with @field_validator, computed fields, and JSON Schema generation — making them a complete solution for data contracts.
TypedDict
TypedDict is a typing construct that describes the shape of a dictionary without adding any runtime overhead. A TypedDict class is just a regular dict at runtime — the type information is used only by static type checkers like mypy and Pyright.
Use TypedDict when you want to add type hints to existing dictionary-based code without refactoring it into classes, or when interfacing with libraries that expect plain dicts. TypedDict is also useful for typing JSON responses from requests or httpx when you don't want to pull in Pydantic as a dependency.
Type Inference Rules
The converter applies these rules to map JSON types to Python:
- Strings become
str - Integers (numbers without decimals) become
int - Floats (numbers with decimals) become
float - Booleans become
bool - null makes the field
Optional[X]orX | None - Arrays become
list[X]where X is the inferred element type - Nested objects generate separate classes
- Empty arrays become
list[Any] - Mixed-type arrays become
list[Any]
Optional vs Union None Syntax
Python offers two ways to express nullable types. The traditional approach uses Optional[str] from the typing module. Python 3.10 introduced the more concise str | None syntax (PEP 604). Both are equivalent — this tool lets you choose via the Optional toggle. If you're targeting Python 3.9 or earlier, use Optional. For 3.10+, the union syntax is generally preferred for its readability.
Tips for Working with Generated Code
The generated code is a starting point. In real projects, you'll often want to add default values, custom validators (Pydantic), or factory functions (dataclasses). Consider renaming classes to match your domain language. For Pydantic models receiving data from APIs with camelCase keys, use model_config = ConfigDict(alias_generator=to_camel) to map between Python snake_case fields and JSON camelCase keys automatically.
When to Use Each Approach
Choose dataclasses when you want a lightweight, dependency-free solution for internal data structures — configuration objects, domain models, and value objects within your application. Choose Pydantic v2 when data arrives from external sources that you cannot trust — HTTP request bodies, configuration files, third-party API responses — where runtime validation prevents bad data from propagating through your system. Choose TypedDict when you need to type-annotate existing dictionary-heavy code incrementally, or when the consuming code expects plain dicts (common in legacy codebases and some libraries).
Related Tools
Generate TypeScript interfaces from JSON with the JSON to TypeScript Converter. Validate your JSON before converting with the JSON Validator. Format messy JSON with the JSON Formatter. Generate a JSON Schema from sample data with the JSON Schema Generator.
Frequently Asked Questions
- What is the difference between dataclass, Pydantic, and TypedDict?
- Python dataclasses are lightweight classes for structured data with type hints and auto-generated __init__, __repr__, and __eq__ methods. Pydantic models add runtime validation — they parse and coerce incoming data to match your schema. TypedDict is purely for type-checking dictionaries at static analysis time without adding any runtime behavior.
- When should I use Pydantic instead of dataclass?
- Use Pydantic when you need runtime data validation, such as parsing API responses, form submissions, or config files. Pydantic automatically coerces types (e.g., "42" becomes 42 for an int field) and raises clear errors on invalid data. Use dataclasses when you just need a structured container without validation overhead.
- How does the tool handle null values in JSON?
- JSON null values are mapped to Optional[X] when the Optional toggle is enabled, or X | None using PEP 604 syntax when disabled. If a field is always null, its type becomes Optional[Any] since the actual type cannot be inferred from null alone.
- What does "from __future__ import annotations" do?
- This import, available since Python 3.7, makes all type annotations lazy (evaluated as strings). It allows forward references — you can use a class name in a type hint before the class is defined. It also enables using built-in types like list[str] and dict[str, int] as type hints in Python 3.7-3.8 without importing from typing.
- How are nested JSON objects converted?
- Each nested JSON object generates a separate Python class. The field in the parent class references the nested class by name. Classes are ordered so dependencies appear before the classes that reference them.
- Can I use this output directly in my Python project?
- Yes. The generated code is valid Python that you can paste directly into a .py file. For dataclasses, you need Python 3.7+. For Pydantic v2, you need the pydantic package installed (pip install pydantic). For TypedDict, you need Python 3.8+ or typing_extensions.
- How are JSON arrays converted to Python types?
- Arrays of a single type become list[str], list[int], etc. Arrays of objects generate a separate class for the item type. Empty arrays become list[Any] since the item type cannot be determined. Arrays with mixed types also become list[Any].
- Is my JSON data sent to a server?
- No. All conversion happens entirely in your browser using JavaScript. Your JSON data never leaves your machine.
Use this tool from AI agents.
The CodeTidy MCP Server lets Claude, Cursor, and other AI agents
use this tool and 46 others directly. One command: npx @codetidy/mcp