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