Dataclasses JSON

0.6.7 · active · verified Sat Mar 28

Dataclasses-json provides a simple API for encoding and decoding Python dataclasses to and from JSON. It extends Python's built-in `dataclasses` module with automatic JSON serialization and deserialization capabilities, supporting features like custom field configurations, letter case conversion, schema validation, and flexible handling of undefined parameters. The library is actively maintained with frequent minor releases, with the current stable version being 0.6.7.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a dataclass, apply the `@dataclass_json` decorator, and then use the generated `to_json()` and `from_json()` methods for serialization and deserialization.

from dataclasses import dataclass
from dataclasses_json import dataclass_json
import json

@dataclass_json
@dataclass
class Person:
    name: str
    age: int
    city: str

# Encoding to JSON
person_instance = Person(name='Alice', age=30, city='New York')
json_string = person_instance.to_json(indent=2)
print(f"Serialized JSON:\n{json_string}")

# Decoding from JSON
raw_json = '{"name": "Bob", "age": 25, "city": "London"}'
decoded_person = Person.from_json(raw_json)
print(f"Deserialized Person: {decoded_person}")

view raw JSON →