python - json.dumps\u 将 unicode 转义为 utf8

标签 python unicode encoding utf-8

我来自这个old discussion ,但解决方案并没有太大帮助,因为我的原始数据编码不同:

我的原始数据已经用 unicode 编码,我需要输出为 UTF-8

data={"content":u"\u4f60\u597d"}

当我尝试转换为 utf 时:

json.dumps(data, indent=1, ensure_ascii=False).encode("utf8")

我得到的输出是 "content": "ä½ å¥½" 预期的输出应该是 "content": "你好"

我在没有 ensure_ascii=false 的情况下尝试过,输出变成了普通的未转义 "content": "\u4f60\u597d"

如何将之前的\u 转义 json 转换为 UTF-8?

最佳答案

拥有 UTF-8 JSON 数据:

>>> import json
>>> data = {'content': u'\u4f60\u597d'}
>>> json.dumps(data, indent=1, ensure_ascii=False)
u'{\n "content": "\u4f60\u597d"\n}'
>>> json.dumps(data, indent=1, ensure_ascii=False).encode('utf8')
'{\n "content": "\xe4\xbd\xa0\xe5\xa5\xbd"\n}'
>>> print json.dumps(data, indent=1, ensure_ascii=False).encode('utf8')
{
 "content": "你好"
}

我的终端碰巧配置为处理 UTF-8,因此将 UTF-8 字节打印到我的终端会产生所需的输出。

但是,如果您的终端设置为此类输出,则您的终端会显示“错误”字符:

>>> print json.dumps(data, indent=1,  ensure_ascii=False).encode('utf8').decode('latin1')
{
 "content": "你好"
}

注意我是如何将数据解码为 Latin-1 以故意误读 UTF-8 字节的。

这不是 Python 问题;这是一个问题,与您在用于读取这些字节的任何工具中处理 UTF-8 字节的方式有关。

关于python - json.dumps\u 将 unicode 转义为 utf8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620471/

相关文章:

python - 如何使 random.choice 包含不选择?

python - 兄弟包导入

javascript - 为什么这段代码会抛出 ReferenceError : test is not defined?

Python 获取 Base64 编码的字节字符串作为字节串

python - 在python中生成多个时间间隔内的时间戳的随机列表

json - 在 Go JSON 中转义 unicode 字符,以便输出与 Python 匹配

python - 比较Python中的字符串: String X is ASCII,和字符串Y是UTF

python - CSV 文件的 Unicode 到 UTF8 - Python 通过 xlrd

mysql - ASP.NET MVC + MySQL 中的编码问题

python - 使用Python创建RTP数据包