我如何使用 Python 将字节数组转换成 JSON 格式?
需要解码字节对象来生成一个字符串。这可以通过 string 类的 decode 函数完成,该函数将接受你要解码的编码。
示例
my_str = b"Hello" # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding
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}"
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP