Last active
December 21, 2015 17:29
-
-
Save petrushev/6340736 to your computer and use it in GitHub Desktop.
Serializer + object hook for Decimal and date 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 json import loads, dumps, JSONEncoder | |
from decimal import Decimal | |
import datetime | |
class Encoder(JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, Decimal): | |
return '__decimal__' + str(obj) | |
if isinstance(obj, datetime.date): | |
return '__date__' + obj.strftime('%Y-%m-%d') | |
return JSONEncoder.default(self, obj) | |
def object_hook(dict_): | |
for key, val in dict_.items(): | |
if val.startswith('__decimal__'): | |
val = Decimal(val.replace('__decimal__', '')) | |
dict_[key] = val | |
elif val.startswith('__date__'): | |
val = val.replace('__date__', '') | |
val = datetime.datetime.strptime(val, '%Y-%m-%d').date() | |
dict_[key] = val | |
return dict_ | |
if __name__=='__main__': | |
obj = {'d': Decimal('1.345457568'), 'dt': datetime.date.today()} | |
obj_ser = dumps(obj, cls=Encoder) | |
obj2 = loads(obj_ser, object_hook=object_hook) | |
print obj==obj2 | |
print obj_ser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment