简体   繁体   中英

Pass user built json encoder into Flask's jsonify

I want to pass a numpy JSON serializer I wrote into Flask's jsonify function, but I cannot find a way to do this. I cannot use json.dumps , because I have to set the status_code of the Flask response when handling an error message. Is there a way to pass the JSON serializer in as a parameter, similar to using the cls parameter in json.dumps as shown here: Convert numpy type to python ? My code is below; thanks.

import json
import numpy as np
from flask import Flask, jsonify

class JSON_Improved(json.JSONEncoder):
    '''
    Used to help jsonify numpy arrays or lists that contain numpy data types.
    '''
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

app = Flask(__name__)
@app.errorhandler(ErrorMessage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

You can custom the json encoder of Flask app with app.json_encoder = JSON_Improved . JSON_Improved inherit from flask.json.JSONEncoder

class JSON_Improved(JSONEncoder):

    pass

There is a Flask Snippets about it in https://web.archive.org/web/20190128005233/http://flask.pocoo.org/snippets/119

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM