Base 64在Python中编码JSON变量

Ash*_*Ksh 7 python base64 json python-3.x

我有一个存储json值的变量.我想在Python中使用base64编码.但抛出错误'不支持缓冲区接口'.我知道base64需要一个字节来转换.但是因为我是Python中的新手,不知道如何将json转换为base64编码的字符串.是否有直接的方法来做到这一点?

dan*_*ano 15

在Python 3.x中,您需要将str对象转换为bytes对象以便base64能够对它们进行编码.您可以使用以下str.encode方法执行此操作:

>>> import json
>>> d = {"alg": "ES256"} 
>>> s = json.dumps(d)  # Turns your json dict into a str
>>> print(s)
{"alg": "ES256"}
>>> type(s)
<class 'str'>
>>> base64.b64encode(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/base64.py", line 56, in b64encode
    raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
>>> base64.b64encode(s.encode('utf-8'))
b'eyJhbGciOiAiRVMyNTYifQ=='
Run Code Online (Sandbox Code Playgroud)

如果将输出传递your_str_object.encode('utf-8')base64模块,则应该可以对其进行编码.