utf-8中的python jsonify字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14853694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:39:55  来源:igfitidea点击:

python jsonify dictionary in utf-8

pythonjsonutf-8flask

提问by Beka

I want to get json data into utf-8

我想将 json 数据转换为 utf-8

I have a list my_list = []

我有一个清单 my_list = []

and then many appends unicode values to the list like this

然后许多人像这样将 unicode 值附加到列表中

my_list.append(u'????')

return jsonify(result=my_list)

and it gets

它得到

{
"result": [
"\u10e2\u10d4\u10e1\u10e2",
"\u10e2\u10dd\u10db\u10d0\u10e8\u10d5\u10d8\u10da\u10d8"
]
}

采纳答案by Martijn Pieters

Use the standard-library jsonmoduleinstead, and set the ensure_asciikeyword parameter to False when encoding, or do the same with flask.json.dumps():

改用标准库json模块,并ensure_ascii在编码时将关键字参数设置为 False,或使用以下方法执行相同操作flask.json.dumps()

>>> data = u'\u10e2\u10d4\u10e1\u10e2'
>>> import json
>>> json.dumps(data)
'"\u10e2\u10d4\u10e1\u10e2"'
>>> json.dumps(data, ensure_ascii=False)
u'"\u10e2\u10d4\u10e1\u10e2"'
>>> print json.dumps(data, ensure_ascii=False)
"????"
>>> json.dumps(data, ensure_ascii=False).encode('utf8')
'"\xe1\x83\xa2\xe1\x83\x94\xe1\x83\xa1\xe1\x83\xa2"'

Note that you still need to explicitly encode the result to UTF8 because the dumps()function returns a unicodeobject in that case.

请注意,您仍然需要将结果显式编码为 UTF8,因为在这种情况下该dumps()函数返回一个unicode对象。

You can make this the default (and use jsonify()again) by setting JSON_AS_ASCIIto Falsein your Flask app config.

您可以jsonify()通过在 Flask 应用程序配置中将其设置JSON_AS_ASCII为 False使其成为默认值(并再次使用)。

WARNING: do not include untrusted data in JSON that is not ASCII-safe, and then interpolate into a HTML template or use in a JSONP API, as you can cause syntax errors or open a cross-site scripting vulnerability this way. That's because JSON is not a strict subset of Javascript, and when disabling ASCII-safe encoding the U+2028 and U+2029 separators will not be escaped to \u2028and \u2029sequences.

警告:不要在非 ASCII 安全的 JSON 中包含不受信任的数据,然后插入 HTML 模板或在 JSONP API 中使用,因为这样可能导致语法错误或打开跨站点脚本漏洞。这是因为JSON 不是 Javascript 的严格子集,并且在禁用 ASCII 安全编码时, U+2028 和 U+2029 分隔符不会转义为\u2028\u2029序列。

回答by Osvaldo Colina

Use the following config to add UTF-8 support:

使用以下配置添加 UTF-8 支持:

app.config['JSON_AS_ASCII'] = False

回答by robus gauli

If you still want to user flask's json and ensure the utf-8 encoding then you can do something like this:

如果您仍然想使用flask 的json 并确保使用utf-8 编码,那么您可以执行以下操作:

from flask import json,Response
@app.route("/")
def hello():
    my_list = []
    my_list.append(u'????')
    data = { "result" : my_list}
    json_string = json.dumps(data,ensure_ascii = False)
    #creating a Response object to set the content type and the encoding
    response = Response(json_response,content_type="application/json; charset=utf-8" )
    return response

I hope this helps

我希望这有帮助

回答by Ture Friese

In my case the above solution was not sufficient. (Running flask on the GCP App Engine flexible environment). I ended up doing:

就我而言,上述解决方案是不够的。(在 GCP App Engine 柔性环境上运行 Flask)。我最终做了:

json_str = json.dumps(myDict, ensure_ascii = False, indent=4, sort_keys=True)
encoding = chardet.detect(json_str)['encoding']
json_unicode = json_str.decode(encoding)
json_utf8 = json_unicode.encode('utf-8')
response = make_response(json_utf8)
response.headers['Content-Type'] = 'application/json; charset=utf-8'
response.headers['mimetype'] = 'application/json'
response.status_code = status