JSON conversion
The JSONDataclass mixin provides automatic conversion to and from JSON.
to_dict/from_dictconvert to and from a Python dict.to_json/from_jsonconvert to and from a JSON file-like object.save/loadconvert to and from a JSON file-like object or path.to_json_string/from_json_stringconvert to and from a JSON string.
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
JSONDataclassis configured to use the default JSON settings provided by Python's standardjsonlibrary. This allows out-of-range float values likenanandinfto be represented asNaNandInfinity, which are not strictly part of the JSON standard. To disallow these values, you can passallow_nan=Falsewhen callingto_jsonorto_json_string, which will raise aValueErrorif such values occur.