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
Approach 1: Class decorator
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class Person:
name: str
lidatong = Person('lidatong')
# Encoding to JSON
encoded_lidatong = lidatong.to_json()
assert encoded_lidatong == '{"name": "lidatong"}'
# Decoding from JSON
decoded_lidatong = Person.from_json('{"name": "lidatong"}')
assert decoded_lidatong == lidatong
Note that the @dataclass_json
decorator must be stacked above the @dataclass
decorator (order matters!)
Approach 2: Inherit from a mixin
from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin
@dataclass
class Person(DataClassJsonMixin):
name: str
lidatong = Person('lidatong')
assert Person.from_json(lidatong.to_json()) == lidatong
Pick whichever approach suits your taste. The differences in implementation are invisible in usage.
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.13-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cc1c4dd30fe9296ec7dc6eb2435dd8836d306455cf1a4ce0d044ee9402346c83 |
|
MD5 | 6f2d556f0146b908120b73910697e640 |
|
BLAKE2b-256 | 615602d8f4c765cfc7df631380101f42bcdcac6d175e92645dad7d7341fe2ded |