如何在 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}"
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP