How to overcome “datetime.datetime not JSON serializable”?

后端 未结 30 3543
梦谈多话
梦谈多话 2020-11-22 03:31

I have a basic dict as follows:

sample = {}
sample[\'title\'] = \"String\"
sample[\'somedate\'] = somedatetimehere
         


        
30条回答
  •  庸人自扰
    2020-11-22 03:58

    If you are using the result in a view be sure to return a proper response. According to the API, jsonify does the following:

    Creates a Response with the JSON representation of the given arguments with an application/json mimetype.

    To mimic this behavior with json.dumps you have to add a few extra lines of code.

    response = make_response(dumps(sample, cls=CustomEncoder))
    response.headers['Content-Type'] = 'application/json'
    response.headers['mimetype'] = 'application/json'
    return response
    

    You should also return a dict to fully replicate jsonify's response. So, the entire file will look like this

    from flask import make_response
    from json import JSONEncoder, dumps
    
    
    class CustomEncoder(JSONEncoder):
        def default(self, obj):
            if set(['quantize', 'year']).intersection(dir(obj)):
                return str(obj)
            elif hasattr(obj, 'next'):
                return list(obj)
            return JSONEncoder.default(self, obj)
    
    @app.route('/get_reps/', methods=['GET'])
    def get_reps():
        sample = ['some text', , 123]
        response = make_response(dumps({'result': sample}, cls=CustomEncoder))
        response.headers['Content-Type'] = 'application/json'
        response.headers['mimetype'] = 'application/json'
        return response
    

提交回复
热议问题