Skip to content

Instantly share code, notes, and snippets.

@raveenb
Last active October 23, 2019 15:44
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 raveenb/117b8ea044acd99139b3082bf7f4f7e7 to your computer and use it in GitHub Desktop.
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
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