Last active
June 22, 2019 19:58
-
-
Save xvzf/2555e935ca606f65a2f6161287fe8922 to your computer and use it in GitHub Desktop.
Jsonify nested datetime objects to isoformat in dicts, lists and dataclasses (Python 3.7)
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
import collections | |
from dataclasses import is_dataclass, asdict | |
from datetime import datetime | |
from ujson import dumps as ujson_dumps | |
def dumps(obj): | |
def convert_to_basic(o): | |
if isinstance(o, dict): | |
return {k: convert_to_basic(v) for k, v in o.items()} | |
elif is_dataclass(o): | |
return convert_to_basic(asdict(o)) | |
elif isinstance(o, list) or isinstance(o, collections.deque): | |
return [convert_to_basic(e) for e in o] | |
elif isinstance(o, datetime): | |
return o.isoformat() | |
else: | |
return o | |
""" Dumps json and formats datetime to isotime """ | |
return ujson_dumps(convert_to_basic(obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment