Skip to content

Instantly share code, notes, and snippets.

@bmwant
Last active April 10, 2016 12:13
Show Gist options
  • Save bmwant/3b7f4075aabc562a4fc870bc45419ce8 to your computer and use it in GitHub Desktop.
Save bmwant/3b7f4075aabc562a4fc870bc45419ce8 to your computer and use it in GitHub Desktop.
Custom JSON Encoder for own type
import json
from json import JSONEncoder
class Custom(object):
def serialize(self):
return 42
class CustomEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, Custom):
return o.serialize()
return o
c = Custom()
json.dumps(c, cls=CustomEncoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment