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
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
json_dunder-0.0.0.tar.gz
(4.7 kB
view details)
Built Distribution
File details
Details for the file json_dunder-0.0.0.tar.gz
.
File metadata
- Download URL: json_dunder-0.0.0.tar.gz
- Upload date:
- Size: 4.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7987cee400ff90497392b1bd5b0534f35248abf6ee4a33ef570abf80a40522c1 |
|
MD5 | 500026f2428c644ecb6d4eb587f84e74 |
|
BLAKE2b-256 | f999d7329304881edb22a5f51344cd1d00c3c7c9fcb278e671e181ed08b3bd4a |
File details
Details for the file json_dunder-0.0.0-py3-none-any.whl
.
File metadata
- Download URL: json_dunder-0.0.0-py3-none-any.whl
- Upload date:
- Size: 4.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.3
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2171d4e64ace82f2ea67ed71c9dc48b6c064eac6b5e202365b055a142d9f0184 |
|
MD5 | ce0e55afebc7b6f4abb381cab47ea445 |
|
BLAKE2b-256 | 5bf720e065e33a038b278deb5d5beb378dc47c8e02fdd77862f9486efb20d82a |