About This Tool
JSON → Python Dataclass drafts typed data classes using the Python standard library. It infers field structure but does not recursively turn JSON dictionaries into dataclass instances. Add loading and validation logic to suit your application.
How to Use It
- Paste JSON. Multiple object samples help identify fields that may be missing.
- Set the root dataclass name.
- Click Convert and review nested types, unions, and the order of required fields before default fields.
- Copy or download the Python file, use it with Python 3.10+, and add deserialization logic.
Examples
- [{"id":1,"name":"Tom"},{"id":2}]: id is required; name can use str | None = None.
- {"matrix":[[1,2],[3,4]],"items":[]}: infer list[list[int]] and list[Any], respectively.
- {"class":"A","first-name":"Tom"}: normalize names and record original keys in comments.
Type Mapping Rules
Strings use str, integers int, decimals or mixed numbers float, booleans bool, and arrays list[T]. Mixed element types can form unions; null-only and unknown values use conservative Any/None types. Missing fields get = None defaults and follow required fields. An explicitly nullable required field is not automatically made optional. Nested dataclasses are declared in dependency order or use explicit forward references, and empty objects produce valid empty classes. Fields use valid snake_case names; keywords get suffixes and naming conflicts are resolved. Rename comments do not configure JSON mapping. Input and output are each limited to 1 MiB, with up to 64 nesting levels, 100,000 nodes, 5,000 merged fields, and 256 types. Unsafe integers, nonfinite numbers, and numbers that underflow to zero produce an error. Other decimals use the browser’s floating-point precision.
Common Uses
- Build structural models for Python data-processing scripts.
- Turn API samples into nested dataclasses.
- Review required, missing, and explicitly null fields.
Privacy
JSON and Python code are inferred and displayed locally. Nothing is uploaded, executed, or written to persistent browser storage.
If you need to keep the results, copy or download them before leaving the page.
FAQ
What is a dataclass?
It is a Python standard-library decorator that generates common methods, including initialization, from field declarations.
Which Python version is required?
The output targets Python 3.10+ and uses modern annotations such as list[T] and A | None.
Why must default fields come last?
In a regular dataclass, a field with a default cannot precede a field without one, or the generated initializer can have an invalid argument order.
How are Python keywords handled?
A key such as class becomes a valid name like class_. A comment preserves the original JSON key, and rename conflicts are resolved.
Does a dataclass automatically restore original JSON field names?
No. Standard dataclasses do not include JSON key mapping or recursive deserialization. Your application must handle renamed fields.