Base 64在Python中对JSON变量进行编码 [英] Base 64 encode a JSON variable in Python

查看:39
本文介绍了Base 64在Python中对JSON变量进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储json值的变量。我想用Python进行base64编码。但是抛出错误"不支持缓冲区接口"。我知道Base64需要一个字节来转换。但由于我是Python中的Newbee,不知道如何将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=='

如果将your_str_object.encode('utf-8')的输出传递给base64模块,则应该能够对其进行正确编码。

这篇关于Base 64在Python中对JSON变量进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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