Last active
April 10, 2016 12:13
-
-
Save bmwant/3b7f4075aabc562a4fc870bc45419ce8 to your computer and use it in GitHub Desktop.
Custom JSON Encoder for own type
This file contains hidden or 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 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