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.

Generaldeep
  • 437
  • 2
  • 12
  • 30

4 Answers4

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)
jiangyx3915
  • 119
  • 3
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"])
Srinivas
  • 136
  • 2
  • 5
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
Hashan Shalitha
  • 835
  • 8
  • 15
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

Olasimbo
  • 965
  • 6
  • 14
  • 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](/help/how-to-answer). – Community May 30 '22 at 12:12