How to convert all Decimals in a Python data structure to string?
You can override the application's JSON encoder by setting the json_encoder
attribute on your application instance:
import flaskapp = flask.Flask(...)app.json_encoder = MyJSONEncoder
Then you can sub-class Flask's JSONEncoder
and override the default()
method to provide support for additional types:
import decimalimport flask.jsonclass MyJSONEncoder(flask.json.JSONEncoder): def default(self, obj): if isinstance(obj, decimal.Decimal): # Convert decimal instances to strings. return str(obj) return super(MyJSONEncoder, self).default(obj)