我想使用 base64 對陣列進行編碼,以便將其轉換為 JSON 以通過 websocket 發送。我在 Python 代碼中的這個 SO 問題中遵循了 ssubotin 的建議。在接收端,在 javascript 中,我使用 window.atob() 來解碼字串。問題是,我必須使用 window.atob() 兩次。這表明我以某種方式對我的資料進行了雙重編碼,從而使字串比所需的長度長了 33%。一些輸出顯示在代碼下方。
# based on https://websockets.readthedocs.io/en/9.0.1/intro.html
import asyncio
import json
from base64 import b64encode, b64decode
import array
myarray = array.array('H', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
class Base64Encoder(json.JSONEncoder):
# ssubotin, https://stackoverflow.com/questions/37225035/serialize-in-json-a-base64-encoded-data
def default(self, o):
if isinstance(o, bytes):
return b64encode(o).decode()
return json.JSONEncoder.default(self, o)
# array_event() creates a message which will be sent over websocket
def array_event():
bytextnd = bytearray()
for x in range(len(myarray)):
bytextnd.extend(myarray[x].to_bytes(2, byteorder='big'))
print(format(b64decode(b64encode(bytextnd)))) # gives bytes en/de-coded
print(json.dumps({"type": "array", "array": b64encode(bytextnd)}, cls=Base64Encoder))
return json.dumps({"type": "array", "array": b64encode(bytextnd)}, cls=Base64Encoder)
Python 輸出: b'\x00\x01\x00\x02\x00\x03\x00\x04 [...] \x00\x0f\x00\x10'
{"type": "array", "array": "QUFFQUFnQURBQVFBQlFBR0FBY0FDQUFKQUFvQUN3QU1BQTBBRGdBUEFCQT0="}
Javascript 將這個作為第一個 window.atob() 的結果產生: AAEAAgADAAQABQAGAAcACAAJAAoACwAMAA0ADgAPABA= 在第二個 window.atob() 和一些我從 Nina Scholz 借來的DataView 和 charCodeAt() 魔法之后正確地產生陣列。
uj5u.com熱心網友回復:
你做的作業太多了...
a = array.array('H',range(1,17))
packed_bytes = struct.pack(f">{len(a)}H",*a)
base64_bytes = base64.b64encode(packed_bytes)
print(base64_bytes)
# b'AAEAAgADAAQABQAGAAcACAAJAAoACwAMAA0ADgAPABA='
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404616.html
標籤:
上一篇:從json中提取資料,使用for回圈追加并另存為CSV
下一篇:無法在控制臺上獲取JSON資料
