Python JSON加载/转储会破坏Unicode? [英] Python JSON loads/dumps breaks Unicode?

查看:89
本文介绍了Python JSON加载/转储会破坏Unicode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将包含unicode字符的字符串作为json转储会产生奇怪的unicode转义序列:

Dumping a string that contains unicode characters as json produces weird unicode escape sequences:

text = "⌂⚘いの法嫁"
print(text) # output: ⌂⚘いの法嫁

import json
json_text = json.dumps(text)
print(json_text) # output: "\u2302\u2698\u3044\u306e\u6cd5\u5ac1"

我想获得此输出:

"⌂⚘いの法嫁"

如何将unicode字符转储为字符而不是转义序列?

How can I dump unicode characters as characters instead of escape sequences?

推荐答案

调用 json.dumps ensure_ascii=False:

json_string = json.dumps(json_dict, ensure_ascii=False)

在Python 2上,返回值将是unicode而不是str,因此您可能需要先encode对其进行任何其他操作.

On Python 2, the return value will be unicode instead of str, so you might want to encode it before doing anything else with it.

这篇关于Python JSON加载/转储会破坏Unicode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆