คุณต้องถอดรหัสวัตถุไบต์เพื่อสร้างสตริง ซึ่งสามารถทำได้โดยใช้ฟังก์ชันถอดรหัสจากคลาสสตริงที่จะยอมรับการเข้ารหัสที่คุณต้องการถอดรหัส
ตัวอย่าง
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}"