Skip to content

Instantly share code, notes, and snippets.

@imanabu
Created August 14, 2019 21:09
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 imanabu/fac49523578ad3ee35bcd3ba7ea0c30b to your computer and use it in GitHub Desktop.
Save imanabu/fac49523578ad3ee35bcd3ba7ea0c30b to your computer and use it in GitHub Desktop.
Python: Allow JSON serialize to work over datetime data type
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