Reputation: 1383
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?
Upvotes: 8
Views: 11924
Reputation: 168626
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
Upvotes: 21
Reputation: 5632
prepend an u before the quotes, e.g. u'quote bla bla bla'
Upvotes: 0