在Python2中
import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)
>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'
我想在python3中得到同样的“输出”:
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编码:
相关问题 更多 >
编程相关推荐