Skip to main content

Python package for making your classes easy encodable to JSON string and vice-versa

Project description

Lint & Test PyPI version Downloads count

jsonabler

Python package for making your classes easy encodable to JSON string and vice-versa.

Getting started

Requirements

  • Python >= 3.8

Installation

pip install jsonabler

Usage

Making a Jsonable

Make your class extends the Jsonable interface and implements get_jsonable_data and from_jsonable_data methods with the encoding/decoding logic.

from jsonabler import Jsonable, jsonabled 

@jsonabled
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'])

Registering a Jsonable

For decoding your Jsonable classes, you need to register it.

Decorating your classes with the @jsonabled decorator

from jsonabler import Jsonable, jsonabled 

@jsonabled
class Foo(Jsonable):
    ...

Calling register_jsonables method passing class types

from jsonabler import Jsonable, register_jsonables 

class Foo(Jsonable):
    ...

if __name__ == '__main__':
    register_jsonables({Foo})

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 loads method passing the JSON string.

from jsonabler import loads, JsonableDecodeError, JsonableNotRegisteredError
from json import JSONDecodeError

def download_foo() -> 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:  
        ...

License

Distributed under the MIT License. See LICENSE file for more information.

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.2.2.tar.gz (4.3 kB view hashes)

Uploaded Source

Built Distribution

jsonabler-0.2.2-py3-none-any.whl (4.6 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