0

I am trying to return return a list of dictionaries as part of a get request. I'm calling the function below.

def get_data(id): selected_data = Database.get_date(id) json.dumps(selected_data, default=str) return jsonify({'data': selected_data}) 

selected_data is like

[{'date': datetime.date(2019, 1, 15), 'id': 1, 'name': 'John '}, {'date': datetime.date(2019, 1, 11), 'id': 2, 'name': 'Jane'}] 

But, I am getting the error below

TypeError(repr(o) + " is not JSON serializable") TypeError: datetime.date(2019, 1, 15) is not JSON serializable

I've tried using json.dumps like this stack overflow thread suggests but still getting the same error.

Any help is appreciated.

2
  • 1
    before jsonifty(), transform datetime.date to string or timestamp. Commented Mar 8, 2019 at 1:23
  • hey, ended up doing this. Thank you for responding. Commented Mar 8, 2019 at 2:14

4 Answers 4

3

You should realize a customer JSONEncoder

import json from datetime import date from datetime import datetime class JsonExtendEncoder(json.JSONEncoder): """ This class provide an extension to json serialization for datetime/date. """ def default(self, o): """ provide a interface for datetime/date """ if isinstance(o, datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(o, date): return o.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, o) if __name__ == '__main__': d = {'now': datetime.now(), 'today': date.today(), 'i': 100} ds = json.dumps(d, cls=JsonExtendEncoder) print "ds type:", type(ds), "ds:", ds l = json.loads(ds) 
Sign up to request clarification or add additional context in comments.

1 Comment

It's a good idea to use isoformat instead of strftime, since it's a web standard that a lot of JavaScript libraries like.
1

Try one of the following

selected_data["date"] = selected_data["date"].isoformat() selected_data["date"] = selected_data["date"].strftime("%Y-%m-%d %H:%M:%S:%f") selected_data["date"] = str(selected_data["date"]) 

1 Comment

this worked, selected_data["date"] = selected_data["date"].isoformat(). Accepting answer, thank you
1

Here's my approach to this. For flask and flask-restful users

import json # import json at the top # inside your def use this code jsonObj = json.dumps(my_dictionary, indent=1, sort_keys=True, default=str) return json.loads(jsonObj), 200 

Comments

0

if the string format is ok to return then convert the time and date field to string before sending

for i in range(len(selected_data)): selected_data[i]["date"] = str(selected_data[i]["date"]) 

then it will work fine

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.