Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง Bytes Array เป็น JSON Format ใน Python

คุณต้อง decode bytes object เพื่อผลิต string สามารถทำได้โดยใช้ฟังก์ชัน decode จาก string class ที่จะรับ encoding ที่คุณต้องการ decode

ตัวอย่าง

my_str = b"Hello"  # b หมายถึง byte string
new_str = my_str.decode('utf-8')  # Decode ด้วย utf-8 encoding
print(new_str)

ผลลัพธ์

Hello

เมื่อคุณได้ bytes เป็น string แล้ว คุณสามารถใช้เมธอด JSON.dumps เพื่อแปลง string object เป็น JSON

ตัวอย่าง

my_str = b'{"foo": 42}'  # b หมายถึง byte string
new_str = my_str.decode('utf-8')  # Decode ด้วย utf-8 encoding
import json
d = json.dumps(my_str)
print(d)

ผลลัพธ์

"{\"foo\": 42}"