Skip to content

Instantly share code, notes, and snippets.

@berdario
Created October 9, 2015 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berdario/65e45d033913de1a2405 to your computer and use it in GitHub Desktop.
Save berdario/65e45d033913de1a2405 to your computer and use it in GitHub Desktop.
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