Last active
December 24, 2015 02:59
-
-
Save treyhunner/6734816 to your computer and use it in GitHub Desktop.
Using single-dispatch generic functions (PEP 443) to implement an extensible JSON encoder To use with Python 2.6 to 3.3, install singledispatch from PyPI.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from decimal import Decimal | |
from json_singledispatch import encode | |
@encode.register(set) | |
def encode_set(obj): | |
return encode(list(obj)) | |
@encode.register(Decimal) | |
def encode_decimal(obj): | |
return encode(str(obj)) | |
print encode({'key': "value"}) | |
print encode({5, 6}) | |
print encode(Decimal("5.6")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from singledispatch import singledispatch | |
class _CustomEncoder(json.JSONEncoder): | |
def default(self, obj): | |
for type_, handler in encode.registry.items(): | |
if isinstance(obj, type_) and type_ is not object: | |
return handler(obj) | |
return super(_CustomEncoder, self).default(obj) | |
@singledispatch | |
def encode(obj, **kwargs): | |
return json.dumps(obj, cls=_CustomEncoder, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment