Make your classes Jsonable
Project description
jsonabler
A simple Python object to JSON string encoder/decoder.
Making a Jsonable
Make your class extends Jsonable
and implements get_jsonable_data
and from_jsonable_data
methods with the encoding/decoding logic.
from jsonabler import Jsonable
class Foo(Jsonable):
def __init__(self, bar: str):
self.__bar = bar
# ...
def get_jsonable_data(self) -> dict:
return {
'bar': self.__bar,
}
@classmethod
def from_jsonable_data(cls, data: dict) -> Jsonable:
return cls(data['bar'])
Encoding a Jsonable
Call dumps
method passing a Jsonable object.
from jsonabler import dumps
def upload_foo(foo: Foo) -> None:
json_string = dumps(foo)
# transmit your JSON string
...
Encoded Foo
[
'Foo',
{
'bar': "abc",
}
]
Decoding a Jsonable
- Call
register_jsonable
method for registering the Jsonables types; - Call
loads
method passing the JSON string.
from jsonabler import register_jsonables, loads, JsonableDecodeError, JsonableNotRegisteredError
from json import JSONDecodeError
def download_foo() -> Foo:
# register Jsonable types for decoding
register_jsonables({Foo})
# receive JSON string encoded Foo object
...
try:
return loads(json_string)
# not a valid encoded JSON string
except JSONDecodeError:
...
# the Jsonable type of the encoded object was not registered
except JsonableNotRegisteredError:
...
# something went wrong while decoding the object
except JsonableDecodeError:
...
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
jsonabler-0.1.3.tar.gz
(3.9 kB
view hashes)
Built Distribution
Close
Hashes for jsonabler-0.1.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f4cf8aff36791f8ff746f81b661025687c624d31cb8920278c3d617e62cd6faf |
|
MD5 | a64720c0dc032f9973dbcafc54c7ab4c |
|
BLAKE2b-256 | 22fbb1455ce7c036343dcad7d1bf007b489c145d54796b62e02f39c1653ab43a |