如何在 Python 中将字节数组转换为 JSON 格式?
pythonjsonprogramming更新于 2025/8/24 5:32:17
您需要解码字节对象以生成字符串。这可以使用字符串类中的解码函数来完成,该函数将接受您想要解码的编码。
示例
my_str = b"Hello" # b 表示它是一个字节字符串
new_str = my_str.decode('utf-8') # 使用 utf-8 编码解码
print(new_str)
输出
这将给出输出
Hello
将字节作为字符串后,您可以使用 JSON.dumps 方法将字符串对象转换为 JSON。
示例
my_str = b'{"foo": 42}' # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding
import json
d = json.dumps(my_str)
print(d)
输出
这将给出输出 −
"{\"foo\": 42}"
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

