Skip to main content

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

  1. Call register_jsonable method for registering the Jsonables types;
  2. 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)

Uploaded Source

Built Distribution

jsonabler-0.1.3-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