json.dumps转义了unicode到utf8

2024-06-16 09:00:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自这个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"

如何将先前转义的json转换为UTF-8?


Tags: json编码data原始数据asciiunicodecontent解决方案
2条回答

您有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": "你好"
}

注意我如何将数据解码成拉丁语1,故意误读UTF-8字节。

这不是一个Python问题;这是一个关于如何使用任何工具读取这些字节来处理UTF-8字节的问题。

在python2中,它工作;但是在python3中,print将输出如下:

>>> b'{\n "content": "\xe4\xbd\xa0\xe5\xa5\xbd"\n}'

不要使用encode('utf8')

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

或者使用sys.stdout.buffer.write而不是print

>>> import sys
>>> import json
>>> data = {'content': u'\u4f60\u597d'}
>>> sys.stdout.buffer.write(json.dumps(data, indent=1, 
ensure_ascii=False).encode('utf8') + b'\n')
{
 "content": "你好"
}

Write UTF-8 to stdout, regardless of the console's encoding

相关问题 更多 >