Created
October 9, 2015 09:58
-
-
Save berdario/65e45d033913de1a2405 to your computer and use it in GitHub Desktop.
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 functools import singledispatch | |
from collections import Iterable | |
from json import JSONEncoder, dumps | |
json_converter = singledispatch(JSONEncoder().default) | |
json_converter.register(Iterable)(list) | |
class A: | |
def __init__(self, a, b): | |
self.a = a | |
self.b = b | |
@json_converter.register(A) | |
def _(a): | |
return a.__dict__ | |
print(dumps([{1}], default=json_converter)) | |
print(dumps([A(1,2)], default=json_converter)) | |
# I tried to use this to get a generic and extensible way to serialize stuff to json, but when plugging this inside a JSONEncoder subclass for use with a Flask app, the encoder was apparently ignored :/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment