如何在python3中json.dumps字节对象

2024-05-15 11:35:57 发布

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

在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

Tags: textimportjsonobjbyteoutopsencode