Skip to main content

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
lidatong.to_json()  # '{"name": "lidatong"}'

# Decoding from JSON
Person.from_json('{"name": "lidatong"}')  # Person(name='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')

# A different example from Approach 1 above, but usage is the exact same
assert Person.from_json(lidatong.to_json()) == lidatong

Pick whichever approach suits your taste. The differences in implementation are invisible in usage.

How do I...

Encode or decode a JSON array containing instances of my Data Class?

from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Person:
    name: str

Encode

people_json = [Person('lidatong')]
Person.schema().dumps(people_json, many=True)  # '[{"name": "lidatong"}]'

Decode

people_json = '[{"name": "lidatong"}]'
Person.schema().loads(people_json, many=True)  # [Person(name='lidatong')]

Encode or decode into Python lists/dictionaries rather than JSON?

This can be by calling .schema() and then using the corresponding encoder/decoder methods, ie. .load(...)/.dump(...).

Encode into a single Python dictionary

person = Person('lidatong')
Person.schema().dump(person)  # {"name": "lidatong"}

Encode into a list of Python dictionaries

people = [Person('lidatong')]
Person.schema().dump(people, many=True)  # [{"name": "lidatong"}]

Decode a dictionary into a single dataclass instance

person_dict = {"name": "lidatong"}
Person.schema().load(person_dict)  # Person(name='lidatong')

Decode a list of dictionaries into a list of dataclass instances

people_dicts = [{"name": "lidatong"}]
Person.schema().load(people_dicts, many=True)  # [Person(name='lidatong')]

Explanation

Briefly, on what's going on under the hood in the above examples: calling .schema() will have this library generate a marshmallow schema for you. It also fills in the corresponding object hook, so that marshmallow will create an instance of your Data Class on load (e.g. Person.schema().load returns a Person) rather than a dict, which it does by default in marshmallow.

Marshmallow interop

Using the dataclass_json decorator or mixing in DataClassJsonMixin will provide you with an additional method .schema().

.schema() generates a schema exactly equivalent to manually creating a marshmallow schema for your dataclass. You can reference the marshmallow API docs to learn other ways you can use the schema returned by .schema().

You can pass in the exact same arguments to .schema() that you would when constructing a PersonSchema instance, e.g. .schema(many=True), and they will get passed through to the marshmallow schema.

from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Person:
    name: str

# You don't need to do this - it's generated for you by `.schema()`!
from marshmallow import Schema, fields

class PersonSchema(Schema):
    name = fields.Str()

A larger example

from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import List

@dataclass_json
@dataclass(frozen=True)
class Minion:
    name: str


@dataclass_json
@dataclass(frozen=True)
class Boss:
    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

dataclasses-json-0.0.24.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dataclasses_json-0.0.24-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file dataclasses-json-0.0.24.tar.gz.

File metadata

  • Download URL: dataclasses-json-0.0.24.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.24.0 CPython/3.7.0

File hashes

Hashes for dataclasses-json-0.0.24.tar.gz
Algorithm Hash digest
SHA256 cd8c990e73770f3c30096ef37e6fd8ab452423daedbe265d64372f6680176aab
MD5 6c6aa47fb82f0b5a11cfef73843f0839
BLAKE2b-256 1eabdf7f742616b410099f363cae31fefe0d3abf6936b4d8b201771826edd13e

See more details on using hashes here.

File details

Details for the file dataclasses_json-0.0.24-py3-none-any.whl.

File metadata

  • Download URL: dataclasses_json-0.0.24-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.24.0 CPython/3.7.0

File hashes

Hashes for dataclasses_json-0.0.24-py3-none-any.whl
Algorithm Hash digest
SHA256 0c9245f396003fd4cd2c2a38e5d3c0bec67e8842fe4a5ac6a26b456f11ee09c0
MD5 2e4914c06f09ac6d80f008b6abba0898
BLAKE2b-256 87e86a05f1ce1071d2391540ba04a5e58ff61e6c71b8fa652f0689677eb97727

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page