JSON conversion
The JSONDataclass
mixin provides automatic conversion to and from JSON.
to_dict
/from_dict
convert to and from a Python dict.to_json
/from_json
convert to and from a JSON file-like object.save
/load
convert to and from a JSON file-like object or path.to_json_string
/from_json_string
convert 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
JSONDataclass
is configured to use the default JSON settings provided by Python's standardjson
library. This allows out-of-range float values likenan
andinf
to be represented asNaN
andInfinity
, which are not strictly part of the JSON standard. To disallow these values, you can passallow_nan=False
when callingto_json
orto_json_string
, which will raise aValueError
if such values occur.