Last active
October 23, 2019 15:44
-
-
Save raveenb/117b8ea044acd99139b3082bf7f4f7e7 to your computer and use it in GitHub Desktop.
Flask JSON numpy Encoder to work with Flask when using Numpy and Timestamp data
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 numpy as np | |
from flask import jsonify | |
from datetime import datetime, timedelta | |
class CustomJSONEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, np.ndarray): return o.tolist() | |
if isinstance(o, np.int64): return int(o) | |
if isinstance(o, set): return list(o) | |
if isinstance(o, (datetime, datetime.date, datetime.time)): return o.isoformat() | |
elif isinstance(o, timedelta): return (datetime.min + o).time().isoformat() | |
return json.JSONEncoder.default(self, o) | |
# here assuming the Flask App is called app | |
app.json_encoder = CustomJSONEncoder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment