我如何使用 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}"

更新時間: 2020 年 3 月 5 日

1.9 萬 + 次瀏覽

啟動你的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.