Base 64 encode a JSON variable in Python(Base 64在Python中对JSON变量进行编码)
本文介绍了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变量进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Base 64在Python中对JSON变量进行编码


猜你喜欢
- 如何将一个类的函数分成多个文件? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01