【发布时间】:2022-01-06 19:00:16
【问题描述】:
我想使用 base64 对数组进行编码,以便将其转换为 JSON 以便通过 websocket 发送。我在我的 Python 代码中遵循了this SO question 中 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= 在我从 Nina Scholz 借来的第二个 window.atob() 和 some DataView and charCodeAt() magic 之后正确地生成了数组。
【问题讨论】: