如何在 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-03-05

1.9 萬次檢視

開啟您的 事業

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.