I'm working on a small flask app in which I want to return strings containing umlauts (in general German special characters, e.g 'ß'). As the default JSONEncoder
in flask has ensure_ascii=True
, this will always convert my string
Hauptstraße 213
to this:
Hauptstra\u00dfe 213
My first approach was to just create a very basic custom JSONEncoder
class NonAsciiJSONEncoder(json.JSONEncoder):
def __init__(self, **kwargs):
super(NonAsciiJSONEncoder, self).__init__(kwargs)
self.ensure_ascii = False
If I use this, by setting
app.json_encoder = NonAsciiJSONEncoder
my return jsonify(...)
will actually return the string containing 'ß'.
However, as ensure_ascii
is an attribute of the default Encoder, I thought it might be better to just change it by setting it to False
app.json_encoder.ensure_ascii = False
This will actually set the property to False which I checked before returning. But somehow, the string is still returned without 'ß' but with \u00df
.
How can this be, as all I'm doing in my custom Encoder, is setting this attribute to False
?
You are setting a class attribute when altering
app.json_encoder.ensure_ascii
, which is not the same thing as an instance attribute.The
JSONEncoder.__init__
method sets an instance attribute toTrue
, as that is the default value for theensure_ascii
argument. Setting the class attribute won't prevent the__init__
method from setting an instance attribute, and it is the instance attribute that wins here.You could just have your subclass set the argument to
False
: