Last active
December 22, 2017 06:32
-
-
Save tritium21/1050ce55f2deb009ec69ce80fd86aa6b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import json | |
| import datetime | |
| class DateTimeDecoder(json.JSONDecoder): | |
| def __init__(self, *args, **kargs): | |
| json.JSONDecoder.__init__( | |
| self, | |
| object_hook=self.dict_to_object, | |
| *args, | |
| **kargs | |
| ) | |
| def dict_to_object(self, d): | |
| if '__type__' not in d: | |
| return d | |
| type = d.pop('__type__') | |
| types = { | |
| 'datetime': datetime.datetime | |
| } | |
| try: | |
| return types[type](**d) | |
| except TypeError: | |
| d['__type__'] = type | |
| return d | |
| class DateTimeEncoder(json.JSONEncoder): | |
| def default(self, obj): | |
| if isinstance(obj, datetime.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, | |
| } | |
| else: | |
| return json.JSONEncoder.default(self, obj) | |
| #use like: | |
| json.loads(some_string, cls=DateTimeDecoder) | |
| json.dumps(some_dict, cls=DateTimeEncoder) | |
| # load and dump variants work the same, just provide the cls argument |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment