簡體   English   中英

使用 Python 3 編碼和解碼二進制數據以包含到 JSON 中

[英]Encoding and decoding binary data for inclusion into JSON with Python 3

我需要決定將二進制元素包含到消息對象中的模式,以便它可以在接收端再次解碼(在我的情況下,Rabbit MQ / AMQP 隊列上的消費者)。

我決定反對通過 JSON 進行多部分 MIME 編碼,主要是因為它看起來像是使用 Thor 的錘子來推動圖釘。 我決定不手動連接部分(二進制和 JSON 連接在一起),主要是因為每次出現新需求時,它都是一個整體的重新設計。 在其中一個字段中使用二進制編碼的 JSON 似乎是一種優雅的解決方案。

我看似可行的(通過比較發送和接收數據的 MD5 總和來確認)解決方案正在執行以下操作:

def json_serialiser(byte_obj):
    if isinstance(byte_obj, (bytes, bytearray)):
        # File Bytes to Base64 Bytes then to String
        return base64.b64encode(byte_obj).decode('utf-8')
    raise ValueError('No encoding handler for data type ' + type(byte_obj))


def make_msg(filename, filedata):
    d = {"filename": filename,
         "datalen": len(filedata),
         "data": filedata}
    return json.dumps(d, default=json_serialiser)

在接收端我只是做:

def parse_json(msg):
    d = json.loads(msg)
    data = d.pop('data')
    return base64.b64decode(data), d


def file_callback(ch, method, properties, body):
    filedata, fileinfo = parse_json(body)
    print('File Name:', fileinfo.get("filename"))
    print('Received File Size', len(filedata))

我的 google-fu 讓我無法確認我在做什么實際上是否有效。 特別是我擔心從二進制數據生成字符串以包含到 JSON 中的行是否正確,例如行return base64.b64encode(byte_obj).decode('utf-8')

似乎我可以使用解碼回二進制數據的捷徑,因為base64.b64decode()方法處理 UTF-8 數據,就好像它是 ASCII 一樣——正如人們所期望的那樣,它來自base64.b64encode() ...但這在所有情況下都是有效的假設嗎?

大多數情況下,我很驚訝無法在網上找到任何這樣做的例子。 也許我的谷歌耐心還在休假!

文檔確認您的方法沒問題。

base64.b64encode(byte_obj).decode('utf-8')是正確的 - base64.b64encode 需要字節作為輸入:

使用 Base64 對類字節對象 s 進行編碼並返回編碼后的字節。

但是base64.b64decode 接受字節或 ascii 字符串:

解碼 Base64 編碼的類字節對象或 ASCII 字符串s並返回解碼后的字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM