使用 Flask 的 jsonify 将 é 显示为 é

问题描述 投票:0回答:2

jsonify('é')
没有打印出我期望的内容。我看到的不是
é
,而是
é

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

@app.route('/')
def test():
    return jsonify('é')

脚本的编码是UTF-8。 UTF-8 JSON 编码应该由

JSON_AS_ASCII = False
激活。

python json python-3.x flask utf-8
2个回答
5
投票

您正在查看转储数据的表示形式。由于您禁用了

JSON_AS_ASCII
,您将获得两个 UTF-8 字节,而不是 ASCII 兼容的 Unicode 转义。无论您选择哪种表示形式,JSON 仍然是 UTF-8,但坚持使用默认值通常更安全。

无论您使用什么方式查看数据,都会将字节误解为 Latin-1,而不是 UTF-8。告诉您正在查看的数据是 UTF-8,并且它看起来是正确的。从 JSON 加载数据,你会发现它仍然是正确的。

from flask import Flask, jsonify, json

app = Flask('example')
app.config['JSON_AS_ASCII'] = True  # default

with app.app_context():
    print(jsonify('é').data)  # b'"\\u00e9"\n', Unicode escape

app.config['JSON_AS_ASCII'] = False

with app.app_context():
    print(jsonify('é').data)  # b'"\xc3\xa9"\n', UTF-8 bytes

# you're viewing the bytes as Latin-1
print(b'\xc3\xa9'.decode('latin1'))  # é

# but it's UTF-8
print(b'\xc3\xa9'.decode('utf8'))  # é

# JSON is always UTF-8
print(json.loads(b'"\\u00e9"\n')  # é
print(json.loads(b'"\xc3\xa9"\n')  # é

0
投票

对于Flask 2.3+,配置方式发生了变化。

使用

app.json.ensure_ascii
(而不是
app.config['JSON_AS_ASCII']

app = Flask(__name__)
app.json.ensure_ascii = False  # <-- this line saves the day

@app.route('/')
def test():
    return jsonify('é')
© www.soinside.com 2019 - 2024. All rights reserved.