Xerobit

JSON to Python Class Converter

Use this json to python class converter to turn any JSON object into clean Python dataclass definitions with accurate type hints. It handles nested objects, arrays, null values and unicode characters automatically. The tool runs locally in the browser so nothing is uploaded to a server.

A valid JSON object (must start with {).

Python classes

from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional, Any

@dataclass
class Root:
    name: str
    age: int
    active: bool

How to use the json to python class converter

  1. Paste your JSON object into the text area. It must begin with an opening brace {.
  2. Set the Root class name to a PascalCase identifier like User or ApiResponse.
  3. The converter immediately generates Python dataclass definitions with correct type hints below.
  4. Copy the output and paste it into your Python file. Add from __future__ import annotations at the top if you need forward references.

How the json to python class conversion works

The tool parses your input using the built-in JSON.parse function and walks the resulting tree to determine Python types. Each JSON object becomes its own @dataclass. Keys are converted to valid Python identifiers by replacing hyphens and spaces with underscores and stripping other invalid characters.

Type mapping follows straightforward rules. A JSON string maps to str, an integer to int, a decimal number to float, a boolean to bool and null to Optional[Any]. Arrays become List[T] where T is inferred from every element, so objects with different keys are merged into one class and keys missing from some objects become Optional. Nested objects trigger generation of a child class whose name is derived from the parent key.

Type mapping reference

This table shows how each JSON type translates into a Python type hint in the generated dataclass.

JSON typeExample valuePython type hint
string"hello"str
integer42int
float3.14float
booleantruebool
nullnullOptional[Any]
array[1, 2]List[int]
object{"a": 1}Child class name

When an array contains mixed types, the converter falls back to List[Any]. Empty arrays produce List[Any] because there is no element to inspect.

Handling nested objects and arrays

Nested structures are flattened into separate class definitions. If your root object has a field called address that is itself an object, the converter creates an Address dataclass and uses it as the type hint in the parent. This keeps every class small and focused.

Arrays of objects work the same way. A field like "items": [{"id": 1}] produces an Item class and types the field as List[Item]. The order of class definitions is bottom-up so that child classes appear before they are referenced, avoiding the need for string-based forward references in most cases.

Key sanitization rules

JSON keys can contain any Unicode character, but Python identifiers have strict rules. The converter applies these transformations in order:

  • Hyphens, spaces and dots are replaced with underscores.
  • Characters that are not ASCII letters, digits or underscores are removed.
  • If the result starts with a digit, an underscore is prepended.
  • If the result matches a Python reserved keyword such as class or return, a trailing underscore is appended.
  • An empty result after filtering becomes _field.

The original JSON key name is preserved in a comment next to the field so you can map it back when serializing.

Using the generated classes

The output relies on the dataclasses module introduced in Python 3.7. Import it at the top of your file along with typing for List, Optional and Any:

from dataclasses import dataclass
from typing import List, Optional, Any

To populate these classes from a JSON string, parse the string with the standard json library and unpack the dictionary into the constructor: User(**json.loads(text)). For deeply nested payloads consider a library like dacite or marshmallow which handles recursive instantiation automatically.

If you need to convert your data to other formats, tools like json to xml or json to sql handle those transformations. For typed languages, sibling converters exist for Java, C#, Go and Kotlin.

Worked examples

ExampleInputResult
Simple user objectJSON input: {"name": "Ada Lovelace", "age": 36, "active": true}; Root class name: Userfrom __future__ import annotations / from dataclasses import dataclass / from typing import List, Optional, Any / @dataclass / class User: / name: str / age: int / active: bool /
Nested addressJSON input: {"person": {"first": "Alan", "last": "Turing"}, "address": {"city": "London", "zip": "W1"}}; Root class name: Recordfrom __future__ import annotations / from dataclasses import dataclass / from typing import List, Optional, Any / @dataclass / class Person: / first: str / last: str / @dataclass / class Address: / city: str / zip: str / @dataclass / class Record: / person: Person / address: Address /
Array of itemsJSON input: {"tags": ["math", "logic"], "scores": [95, 87, 100]}; Root class name: Profilefrom __future__ import annotations / from dataclasses import dataclass / from typing import List, Optional, Any / @dataclass / class Profile: / tags: List[str] / scores: List[int] /

FAQ

Does this json to python class converter support Python 3.10+ union syntax?

The output uses typing module generics like Optional and List for broad compatibility with Python 3.7 and later. You can manually replace Optional[X] with X | None if you target Python 3.10 or newer.

What happens if my JSON is an array at the root level?

If the array holds objects, the converter merges them and generates one class that describes a single element, with keys missing from some objects marked Optional. An array of plain numbers or strings is rejected because there is no record to turn into a class.

Are default values included in the generated classes?

No. The tool generates type hints only. Adding defaults depends on your application logic, so they are left out to keep the output predictable.

How are null values handled?

A JSON null on its own maps to Optional[Any] since the actual type cannot be determined from a null alone. If the same field is null in one array element and a real value in another, the hint becomes Optional of that type.

Is my JSON data sent to a server?

No. Parsing and code generation happen entirely in your browser using JavaScript. Nothing leaves your machine.

Can I use the output with Pydantic?

Yes. Replace the @dataclass decorator with a Pydantic BaseModel subclass and the type hints will work the same way, giving you automatic validation.