Python 2.x和3.x兼容代码,用于通过JSON发送字节数据

-8 python base64 json python-2.7 python-3.x

我有一个base-64编码的字符串.

some_s = base64.encodestring(....)
Run Code Online (Sandbox Code Playgroud)

在Python 2.7中,我可以将这样的字符串序列化为JSON(json.dumps).

在Python 3.3中,some_s'是一个字节字符串,需要首先转换为'str:

some_s2 = str(some_s2, encoding='ascii')
Run Code Online (Sandbox Code Playgroud)

然后some_s2可以序列化为JSON.

不幸的是,Python 2.7不接受编码参数作为str()调用的一部分.

您如何编写使用Python 2.7和Python 3.3运行的转换代码?

Mar*_*ers 5

您可以检测到您的值不是类型str:

some_s = base64.encodestring(....)
if not isinstance(some_s, str):
    some_s = some_s.decode('ascii')
Run Code Online (Sandbox Code Playgroud)

仅在Python 3中是some_s类型bytes.请注意该.decode()方法,而不是str(some_s, encoding='ascii')在Python 2和3中都可以使用的方法.