Created
August 14, 2019 21:09
-
-
Save imanabu/fac49523578ad3ee35bcd3ba7ea0c30b to your computer and use it in GitHub Desktop.
Python: Allow JSON serialize to work over datetime data type
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
def to_serializable(val): | |
""" | |
Allows the JSON serializer to work over datetime data type | |
:param val: | |
:return: | |
""" | |
if isinstance(val, datetime): | |
return val.isoformat() + "Z" | |
vf = type(val).__name__ | |
if vf == "ObjectId": | |
return str(val) | |
# This is the key importance for this to work for other types of data | |
return val.__dict__ | |
# THEN at some point in the code you would pass _to_serializable to json.dump, in this case | |
# "score" is a Plain Python Class, the object can also be a Ptyhon dict type | |
try: | |
with open(ehr_path, 'w') as ehr_file: | |
json.dump(score, ehr_file, indent=3, default=to_serializable) | |
except Exception as why: | |
log.warning(f"ehr record for {ehr_path} save failed due to {why}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment