Skip to main content

Custom json serialization support.

Project description

Easily add custom JSON serialization

Code Example

Defaults

import serial_json as json
import datetime

value = b'Hello World!'  # Bytes are not supported by json normally
assert json.loads(json.dumps(value)) == value

dt = datetime.datetime.now()  # datetimes are not supported by json normally
assert json.loads(json.dumps(dt)) == dt

Custom

Custom serialization using a classes __getstate__ and __setstate__ methods.

import serial_json as json

@json.register
class MyClass(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __eq__(self, other):
        """Compare objects."""
        try:
            return self.x == other.x and self.y == other.y
        except (AttributeError, Exception):
            return False

    def __getstate__(self):
        return {'x': self.x, 'y': self.y}

    def __setstate__(self, state):
        self.x = state.get('x', 0)
        self.y = state.get('y', 0)

my_value = MyClass()
assert json.loads(json.dumps(my_value)) == my_value

Custom serialization with functions instead of a class with getstate and setstate.

import serial_json

class MyClass(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __eq__(self, other):
        """Compare objects."""
        try:
            return self.x == other.x and self.y == other.y
        except (AttributeError, Exception):
            return False

def cls_to_dict(obj):
    return {'x': obj.x, 'y': obj.y}

def cls_from_dict(obj):
    return MyClass(**obj)

# Register the serialize and deserialize functions
serial_json.register(MyClass, cls_to_dict, cls_from_dict)

my_value = MyClass()
assert serial_json.loads(serial_json.dumps(my_value)) == my_value

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

serial_json-1.0.0.tar.gz (6.6 kB view details)

Uploaded Source

File details

Details for the file serial_json-1.0.0.tar.gz.

File metadata

  • Download URL: serial_json-1.0.0.tar.gz
  • Upload date:
  • Size: 6.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.41.1 CPython/3.6.8

File hashes

Hashes for serial_json-1.0.0.tar.gz
Algorithm Hash digest
SHA256 708b61e30fd103e7c388b7f73e3d957c0a90d170866099e37a461e21d1746ec1
MD5 7e0266733c03aa1875d82b57240b4dbe
BLAKE2b-256 d78d0a3d0dd007bd332dc03c0898c381915bb6fec62984ca1aed2aaf88f970fa

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page