Easily serialize dataclasses to and from JSON
Project description
Dataclasses JSON
This library provides a simple API for encoding and decoding dataclasses to and from JSON.
It's recursive (see caveats below), so you can easily work with nested dataclasses.
In addition to the supported types in the py to JSON table, any arbitrary Collection type is supported (they are encoded into JSON arrays, but decoded into the original collection types).
The latest release is compatible with both Python 3.7 and Python 3.6 (with the dataclasses backport).
Quickstart
pip install dataclasses-json
from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin
@dataclass
class MyDataClass(DataClassJsonMixin):
name: str
my_dataclass_instance = MyDataClass('example')
# Encoding to JSON
some_json_string = my_dataclass_instance.to_json()
# Decoding from JSON
MyDataClass.from_json(some_json_string)
A larger example
from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin
from typing import List
@dataclass(frozen=True)
class Minion(DataClassJsonMixin):
name: str
@dataclass(frozen=True)
class Boss(DataClassJsonMixin):
minions: List[Minion]
boss = Boss([Minion('evil minion'), Minion('very evil minion')])
boss_json = """
{
"minions": [
{
"name": "evil minion"
},
{
"name": "very evil minion"
}
]
}
""".strip()
assert boss.to_json(indent=4) == boss_json
assert Boss.from_json(boss_json) == boss
Caveats
Data Classes that contain forward references (e.g. recursive dataclasses) are not currently supported.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for dataclasses_json-0.0.12-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | dd1e6bf7e98e6924849886bf7451e09cfc4f9a1e77ecf64fe79714140fff2f02 |
|
MD5 | 9d149b3c4e9804fef7fc41be69932d11 |
|
BLAKE2b-256 | 1148ef5a7dc88655851c5effced2f3be491a2ddc9e5993767a7a9189069728ce |