Created
December 4, 2012 04:07
-
-
Save majgis/4200488 to your computer and use it in GitHub Desktop.
JSON Encoder and Decoder for datetime and timedelta
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
# Taken from http://taketwoprogramming.blogspot.com/2009/06/subclassing-jsonencoder-and-jsondecoder.html | |
class DateTimeAwareJSONEncoder(JSONEncoder): | |
""" | |
Converts a python object, where datetime and timedelta objects are converted | |
into objects that can be decoded using the DateTimeAwareJSONDecoder. | |
""" | |
def default(self, obj): | |
if isinstance(obj, datetime): | |
return { | |
'__type__' : 'datetime', | |
'year' : obj.year, | |
'month' : obj.month, | |
'day' : obj.day, | |
'hour' : obj.hour, | |
'minute' : obj.minute, | |
'second' : obj.second, | |
'microsecond' : obj.microsecond, | |
} | |
elif isinstance(obj, timedelta): | |
return { | |
'__type__' : 'timedelta', | |
'days' : obj.days, | |
'seconds' : obj.seconds, | |
'microseconds' : obj.microseconds, | |
} | |
else: | |
return JSONEncoder.default(self, obj) | |
class DateTimeAwareJSONDecoder(JSONDecoder): | |
""" | |
Converts a json string, where datetime and timedelta objects were converted | |
into objects using the DateTimeAwareJSONEncoder, back into a python object. | |
""" | |
def __init__(self): | |
JSONDecoder.__init__(self, object_hook=self.dict_to_object) | |
def dict_to_object(self, d): | |
if '__type__' not in d: | |
return d | |
type = d.pop('__type__') | |
if type == 'datetime': | |
return datetime(**d) | |
elif type == 'timedelta': | |
return timedelta(**d) | |
else: | |
# Oops... better put this back together. | |
d['__type__'] = type | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace
__init__
with the following code to prevent the "TypeError: __init__() got an unexpected keyword argument 'encoding'
" :