8

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?

1 Answer 1

10

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 to True, as that is the default value for the ensure_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:

class NonASCIIJSONEncoder(json.JSONEncoder):
    def __init__(self, **kwargs):
        kwargs['ensure_ascii'] = False
        super(NonASCIIJSONEncoder, self).__init__(**kwargs)
Sign up to request clarification or add additional context in comments.

2 Comments

ah, thanks a lot. I had been under the impression that app.json_encoder points to an object, which is obviously not the case
@LawrenceBenson: it is a class, yes, not an instance, because it is passed into the json.dumps() function as the cls argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.