In python2
import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)
>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'
I want to get same 'Out' in 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"}'
In Python3, If there is a way to convert
{"text": "你好"} # first, encoding with gbk, then json.dumps
to
b'{"text": "\xc4\xe3\xba\xc3"}' # json serialized result
If you actually want GBK encoding in Python 3:
import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))
b'{"text": "\xc4\xe3\xba\xc3"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With