Skip to content

Instantly share code, notes, and snippets.

@danielthiel
Created May 23, 2014 11:37
Show Gist options
  • Save danielthiel/6344f7e0eda1e7d0fd52 to your computer and use it in GitHub Desktop.
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
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