Skip to content

Instantly share code, notes, and snippets.

@petrushev
Last active December 21, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrushev/6340736 to your computer and use it in GitHub Desktop.
Save petrushev/6340736 to your computer and use it in GitHub Desktop.
Serializer + object hook for Decimal and date objects
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