Skip to main content

Encode objects with a __json__ dunder method and decode objects with a __from_json__ dunder method.

Project description

Encdoe objects with a __json__ dunder method and decode objects with a __from_json__ dunder method.

import json_dunder

# Use tells json to use this class
coder = json_dunder.JsonDunderTypeCoder().use()

@coder.register
class A:
    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.x == other.x
        return False

    def __json__(self):
        return {"x": self.x}

    @classmethod
    def __from_json__(cls, d: dict):
        return cls(**d)

@coder.register
class B:
    def __init__(self, a, y):
        self.a = a
        self.y = y

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.a == other.a and self.y == other.y
        return False

    def __json__(self):
        return {"a": self.a, "y": self.y}

    @classmethod
    def __from_json__(cls, d: dict):
        return cls(**d)

a = A(1)
b = B(a, 2)

sa = json_dunder.dumps(a)
assert sa == '{"x": 1, "__json_type__": "__main__.A"}'

sb = json_dunder.dumps(b)
assert sb == '{"a": {"x": 1, "__json_type__": "__main__.A"}, "y": 2, "__json_type__": "__main__.B"}'

obj = json_dunder.loads(sa)
assert obj == a

obj = json_dunder.loads(sb)
assert obj.a == a
assert obj == b

Install

pip install json_dunder

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

json_dunder-0.0.0.tar.gz (4.7 kB view hashes)

Uploaded Source

Built Distribution

json_dunder-0.0.0-py3-none-any.whl (4.4 kB view hashes)

Uploaded Python 3

Supported by

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