Skip to content

JSON conversion

The JSONDataclass mixin provides automatic conversion to and from JSON.

Usage Example

Define a JSONDataclass.

from dataclasses import dataclass
from typing import Optional

from fancy_dataclass.json import JSONDataclass


@dataclass
class Person(JSONDataclass):
    name: str
    age: int
    height: float
    hobbies: list[str]
    awards: Optional[list[str]] = None

Convert to/from a Python dict.

>>> person = Person(
    name='John Doe',
    age=47,
    height=71.5,
    hobbies=['reading', 'juggling', 'cycling']
)

# default values are suppressed by default
>>> person.to_dict()
{'name': 'John Doe',
 'age': 47,
 'height': 71.5,
 'hobbies': ['reading', 'juggling', 'cycling']}

# include all the values
>>> person.to_dict(full=True)
{'name': 'John Doe',
 'age': 47,
 'height': 71.5,
 'hobbies': ['reading', 'juggling', 'cycling'],
 'awards': None}

>>> new_person = Person.from_dict(person.to_dict())
>>> new_person == person
True

Convert to/from a JSON string.

>>> person = Person(
    name='John Doe',
    age=47,
    height=71.5,
    hobbies=['reading', 'juggling', 'cycling']
)

>>> json_string = person.to_json_string(indent=2)

>>> print(json_string)
{
  "name": "John Doe",
  "age": 47,
  "height": 71.5,
  "hobbies": [
    "reading",
    "juggling",
    "cycling"
  ]
}

>>> new_person = Person.from_json_string(json_string)
>>> person == new_person
True

Details

🚧 Under construction 🚧

Notes

  • JSONDataclass is configured to use the default JSON settings provided by Python's standard json library. This allows out-of-range float values like nan and inf to be represented as NaN and Infinity, which are not strictly part of the JSON standard. To disallow these values, you can pass allow_nan=False when calling to_json or to_json_string, which will raise a ValueError if such values occur.