Hub/python

Python Dataclass to JSON

Convert dataclasses to and from JSON with type safety.

dataclassjsonserialization
D
Demo User
|Feb 22, 2026|0 views0 imports
View Raw
python
from dataclasses import dataclass, asdict
import json
from typing import Optional

@dataclass
class User:
    name: str
    email: str
    age: Optional[int] = None

    def to_json(self) -> str:
        return json.dumps(asdict(self), indent=2)

    @classmethod
    def from_json(cls, data: str) -> "User":
        return cls(**json.loads(data))

# Usage
user = User(name="Alice", email="[email protected]", age=30)
print(user.to_json())
restored = User.from_json(user.to_json())