Created
October 24, 2017 00:42
-
-
Save vlad-bezden/79642f9326d776c448cf98e5191940c0 to your computer and use it in GitHub Desktop.
JSON Serializer for Python objects not serializable by default (date and datetime)
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 | |
from datetime import date, datetime | |
def to_json(obj): | |
'''JSON serializer for objects not serializable by default''' | |
if isinstance(obj, (datetime, date)): | |
return obj.isoformat() | |
raise TypeError (f'Type {type(obj)} not serializable') | |
data = {'today': date.today(), 'time': datetime.now(), 'life': 42} | |
json_data = json.dumps(data, default=to_json) | |
print(data) | |
print(json_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment