Simplify JSON Encoders and Object Hooks
Project description
# json-object-factory Simplifies building custom encoders and object-hooks for Python’s default JSON implementation.
Installation
$ pip install json-object-factory
Usage
Add encoders and decoders to the registry:
import jsonfactory
class MyJsonHandler(object):
def encode(self, o):
if isinstance(o, MyCustomClass):
return o.serialize()
return None
def decode(self, d):
if 'some_custom_key' in d:
return MyCustomClass(**d)
return d
jsonfactory.Registry.register(MyJsonHandler)
Or use the included decorators:
@jsonfactory.register
class MyOtherJsonHandler(object):
...
@jsonfactory.encoder
def an_encoder_function(o):
...
@jsonfactory.decoder
def a_decoder_function(d):
...
Then use the module’s dumps and loads functions:
json_str = jsonfactory.dumps(obj_dict, indent=2)
new_obj_dict = jsonfactory.loads(json_str)
Notes
The calling signature for encoder functions follows that of the built-in JSONEncoder with one exception:
If no modifications are needed and the object should be passed to the base encoder’s handler, None should be returned. This differs from the normal method of calling super(MyEncoder, self).default(o) (that would most likely be an error since subclassing JSONEncoder isn’t necessary).
The signature for decoder functions follows the object_hook signature in the built-in implementation
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 Distributions
Built Distribution
Hashes for json_object_factory-0.0.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ac23654ea7b25dde97a0ff4429a80cf3e4fabe9a493ff6bafaea9157591939f3 |
|
MD5 | c6bd15c4e1b37518c0837796a47df5d9 |
|
BLAKE2b-256 | ca2d6ccb4606482450758d682a1d2679649e1ef0cd8f210d382c48bbb8a887c5 |