Base 64在Python中对JSON变量进行编码

Base 64在Python中对JSON变量进行编码,python,json,python-3.x,base64,Python,Json,Python 3.x,Base64,我有一个存储json值的变量。我想用Python对其进行base64编码。但是抛出错误“不支持缓冲区接口”。我知道base64需要一个字节来转换。但由于我是Python新手,不知道如何将json转换为base64编码的字符串。有没有直接的方法呢 在Python3.x中,您需要将str对象转换为bytes对象,以便base64能够对它们进行编码。您可以使用str.encode方法执行此操作: >>> import json >>> import base64 &

我有一个存储json值的变量。我想用Python对其进行base64编码。但是抛出错误“不支持缓冲区接口”。我知道base64需要一个字节来转换。但由于我是Python新手,不知道如何将json转换为base64编码的字符串。有没有直接的方法呢

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

>>> import json
>>> import base64
>>> 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=='
导入json >>>导入base64 >>>d={“alg”:“ES256”} >>>s=json.dumps(d)#将json dict转换为str >>>印刷品 {“alg”:“ES256”} >>>类型 >>>base64.b64编码 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 b64encode中的文件“/usr/lib/python3.2/base64.py”,第56行 raise TypeError(“应为字节,而不是%s”%s.\u类\u名称\u) TypeError:应为字节,而不是str >>>base64.b64encode(s.encode('utf-8')) b'eyJhbGciOiAiRVMyNTYifQ=='
如果将
您的\u str_object.encode('utf-8')
的输出传递到
base64
模块,您应该能够对其进行良好的编码。

您可以先对字符串进行编码,例如utf-8,然后对其进行base64编码:

data = '{"hello": "world"}'
enc = data.encode()  # utf-8 by default
print base64.encodestring(enc)

这也适用于2.7:)

这里有两种在python3上工作的方法 encodestring已弃用,建议使用的是encodebytes

import json
import base64


with open('test.json') as jsonfile:
    data = json.load(jsonfile)
    print(type(data))  #dict
    datastr = json.dumps(data)
    print(type(datastr)) #str
    print(datastr)
    encoded = base64.b64encode(datastr.encode('utf-8'))  #1 way
    print(encoded)

    print(base64.encodebytes(datastr.encode())) #2 method

这里有一个函数,您可以输入一个字符串,它将输出一个base64字符串

import base64
def b64EncodeString(msg):
    msg_bytes = msg.encode('ascii')
    base64_bytes = base64.b64encode(msg_bytes)
    return base64_bytes.decode('ascii')

如果我的问题模棱两可,我深表歉意。实际上,我正在尝试构造一个JWS并用Base64编码它。所以我的变量是这样的,header={“alg”:“ES256”}。我尝试做的是base64.b64encode(header)。我发现唯一的解决方案是将一个已经用base64编码的字符串转换为纯文本字符串。谢谢必须
导入base64
first@greg谢谢,修好了。