我怎样才能得到蟒蛇base64编码发挥好使用JSON? [英] How can I get python base64 encoding to play nice with json?

查看:217
本文介绍了我怎样才能得到蟒蛇base64编码发挥好使用JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大的二进制zip文件传输作为一个JSON接口的一部分。我他们转换为base64用于此目的,但我无法背面干净利索阅读如图所示用一个简单的案例在这里:

I have large binary zip files to transport as part of a JSON interface. I've converted them to base64 for this purpose but I'm unable to read them back cleanly as shown with a simple case here:

~ $ ipython --nobanner

In [1]: epub = 'trial/epubs/9780857863812.epub'

In [2]: import base64

In [3]: import json

In [4]: f = open(epub, 'rb')

In [5]: content = f.read()

In [7]: base64.urlsafe_b64decode(base64.urlsafe_b64encode(content)) == content
Out[7]: True


In [8]: base64.urlsafe_b64decode(json.loads(json.dumps(base64.urlsafe_b64encode(content)))) == content
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/paul/wk/evanidus/repo_wc/branches/services/carroll/dev/<ipython console> in <module>()

/usr/lib/python2.6/base64.pyc in urlsafe_b64decode(s)
    110     The alphabet uses '-' instead of '+' and '_' instead of '/'.
    111     """
--> 112     return b64decode(s, '-_')
    113 
    114 

/usr/lib/python2.6/base64.pyc in b64decode(s, altchars)
     69     """
     70     if altchars is not None:
---> 71         s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
     72     try:
     73         return binascii.a2b_base64(s)

/usr/lib/python2.6/base64.pyc in _translate(s, altchars)
     34     for k, v in altchars.items():
     35         translation[ord(k)] = v
---> 36     return s.translate(''.join(translation))
     37 
     38 

TypeError: character mapping must return integer, None or unicode

看来,JSON处理以某种方式破坏的base64内容。

It seems that the json processing is corrupting the base64 content somehow.

推荐答案

的问题是与编码。 JSON返回UTF-8 EN codeD文本其中的base64模块不能处理(就是了ASCII)。因此,修正为en code('ASCII码'),它传递为base64前的JSON德codeD字符串:

The problem was with the encoding. json returns utf-8 encoded text which the base64 module cannot handle (it wants ascii). The correction is therefore to encode('ascii') the json decoded string before passing it to base64:

In [8]: base64.urlsafe_b64decode(
            json.loads(
                json.dumps(base64.urlsafe_b64encode(content))
            )
            .encode('ascii')
        ) == content
Out[7]: True

这篇关于我怎样才能得到蟒蛇base64编码发挥好使用JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆