Flask JSON serializable error because of flask babel
The issue is that your error message is a _LazyString
object returned by lazy_gettext
, not a string. Normally, this wouldn't be an issue because displaying it in a template would call str()
on it, causing it to evaluate the translation. However, you are collecting the objects in error_list
, and then passing them to jsonify
, and json has no serializer for these objects.
You need to tell Flask's JSON serializer how to handle these objects. Write a custom serializer then assign it to app.json_encoder
.
from flask._compat import text_typefrom flask.json import JSONEncoder as BaseEncoderfrom speaklater import _LazyStringclass JSONEncoder(BaseEncoder): def default(self, o): if isinstance(o, _LazyString): return text_type(o) return BaseEncoder.default(self, o)app.json_encoder = JSONEncoder