Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does flask jsonify support UTF-8?

I've been doing experiments using flasks and jsonify. It works. But doesn't support utf-8 chararacters (turkish characters). I'm using a dictionary.

if api_key in key_list:
    quotes = {
                'ataturk':
                ['Hayatta En Hakiki Mursit Ilimdir Fendir',
                 'Birgün benim naciz bedenim'],
                  'mahatma gandhi':
                ['Happiness is when what you think, what you'
                 'say,and what you do are in harmony.']
             }

    get_quote = quotes[karakter(author.lower(), harfler)]

    quote = {
               'quotes': random.choice(get_quote),
            }

    return jsonify(quote)

I've tried encode but it's not working. I got this error in debug mode:

AttributeError: 'dict' object has no attribute 'encode'

How can I solve this problem?

like image 290
Ali Avatar asked Apr 02 '16 20:04

Ali


People also ask

What does Jsonify do in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.


1 Answers

You are correct, jsonify does not support UTF-8 characters. It does, however, support Unicode characters perfectly well.

Consider these two programs:

# http server
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def root():
    return jsonify({'quote':'Birgün'})

if __name__=='__main__':
    app.run(debug=True)

 

# http client
import requests
import unicodedata
r = requests.get('http://localhost:5000/')
j = r.json()
u = j['quote'][4]
print("%s: %d %x %s\n"%(u, len(u), ord(u), unicodedata.name(u)))

As you can see, the http client fetches the JSON, decodes it, and checks the "ü" in "Birgün".

The result should make it clear that the ü survived the end-to-end trip, from a Python3 string, through JSON and HTTP, and back into a Python3 string.

ü: 1 fc LATIN SMALL LETTER U WITH DIAERESIS

EDIT: Having said all of that, there is a configuration option which will force jsonify() to behave as you hope:

app.config['JSON_AS_ASCII'] = False
like image 59
Robᵩ Avatar answered Nov 08 '22 14:11

Robᵩ