Created
May 23, 2014 11:37
-
-
Save danielthiel/6344f7e0eda1e7d0fd52 to your computer and use it in GitHub Desktop.
JSON encoder class with serializer for dates and decimal numbers: serializes json objects without error
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 | |
import datetime | |
import decimal | |
class MyJsonEncoder(json.JSONEncoder): | |
""" JSON Encoder with serializer for dates and decimal numbers """ | |
def default(self, obj): | |
if isinstance(obj, datetime.datetime): | |
return str(obj.isoformat()) | |
elif isinstance(obj, datetime.time): | |
return str(obj.isoformat()) | |
elif isinstance(obj, decimal.Decimal): | |
return float(obj) | |
return json.JSONEncoder.default(self, obj) | |
if __name__ == '__main__': | |
obj = { | |
'time': datetime.time(15), | |
'dt': datetime.datetime.utcnow(), | |
'dec': decimal.Decimal(3.5) | |
} | |
print json.dumps(obj, cls = MyJsonEncoder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment