在python2中
import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)
>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'
我想在 python3 中获得相同的“Out”:
import codecs
byte_obj = "你好".encode("gbk")
x = byte_obj.decode("utf8", "backslashreplace") # ops, it become '\\xc4\\xe3\\xba\\xc3'
x = codecs.escape_encode(byte_obj)[0] # ops, it become b'\\xc4\\xe3\\xba\\xc3'
# fail, I have to concatenate them
b'{"text": "' + u"你好".encode("gbk") + b'"}'
>>> Out: b'{"text": "\xc4\xe3\xba\xc3"}'
在Python3中,如果有办法转换
{"text": "你好"} # first, encoding with gbk, then json.dumps
到
b'{"text": "\xc4\xe3\xba\xc3"}' # json serialized result
最佳答案
如果你真的想在 Python 3 中进行 GBK 编码:
import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))
b'{"text": "\xc4\xe3\xba\xc3"}'
关于python - 如何在python3中json.dumps字节对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44449140/