在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
答案 0 :(得分:5)
如果你真的想在Python 3中使用GBK编码:
import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))
b'{"text": "\xc4\xe3\xba\xc3"}'