Created
September 4, 2011 04:21
-
-
Save deybhayden/1192252 to your computer and use it in GitHub Desktop.
Custom JSON Serialization for Date and Decimal Objects
This file contains 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
from datetime import date, datetime, time | |
from decimal import Decimal | |
def to_json(python_object): | |
""" | |
Adding in custom serialization for Date & Decimal objects. | |
>>> import json | |
>>> from datetime import date, datetime, time | |
>>> from decimal import Decimal | |
>>> json.dumps({'adatetime': datetime(2012, 1, 1, 12, 1, 1)}, default=to_json) | |
'{"adatetime": "2012-01-01 12:01:01"}' | |
>>> json.dumps({'adate': date(2012, 1, 1)}, default=to_json) | |
'{"adate": "2012-01-01"}' | |
>>> json.dumps({'atime': time(12, 1, 1)}, default=to_json) | |
'{"atime": "12:01:01"}' | |
>>> json.dumps({'adecimal': Decimal('1.01')}, default=to_json) | |
'{"adecimal": "1.01"}' | |
""" | |
if (isinstance(python_object, date) | |
or isinstance(python_object, datetime) | |
or isinstance(python_object, time)): | |
return str(python_object) | |
if isinstance(python_object, Decimal): | |
return python_object.to_eng_string() | |
raise TypeError(repr(python_object) + ' is not JSON serializable') | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment