Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển bytes array sang JSON format trong Python

Decode bytes → string (utf-8), sau đó json.dumps().

Bytes → String

my_str = b"Hello"
new_str = my_str.decode('utf-8')
print(new_str)  # Hello

Bytes → JSON

my_str = b'{"foo": 42}'
new_str = my_str.decode('utf-8')
import json
d = json.dumps(my_str)  # Note: dumps string, not parsed dict
print(d)  # "{\\"foo\\": 42}"

Sửa: Nếu muốn parse JSON từ bytes: json.loads(my_str.decode('utf-8')).