Base 64 在 Python 中对 JSON 变量进行编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24831543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base 64 encode a JSON variable in Python
提问by AshKsh
I have a variable that stores json value. I want to base64 encode it in Python. But the error 'does not support the buffer interface' is thrown. I know that the base64 needs a byte to convert. But as I am newbee in Python, no idea as how to convert json to base64 encoded string.Is there a straight forward way to do it??
我有一个存储 json 值的变量。我想在 Python 中对它进行 base64 编码。但是会抛出“不支持缓冲区接口”的错误。我知道 base64 需要一个字节来转换。但是由于我是 Python 新手,不知道如何将 json 转换为 base64 编码的字符串。有没有直接的方法来做到这一点?
采纳答案by dano
In Python 3.x you need to convert your str
object to a bytes
object for base64
to be able to encode them. You can do that using the str.encode
method:
在 Python 3.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=='
If you pass the output of your_str_object.encode('utf-8')
to the base64
module, you should be able to encode it fine.
如果您将 的输出传递your_str_object.encode('utf-8')
给base64
模块,您应该能够对其进行良好的编码。
回答by Jaime Gómez
You could encode the string first, as UTF-8 for example, then base64 encode it:
您可以先对字符串进行编码,例如 UTF-8,然后对它进行 base64 编码:
data = '{"hello": "world"}'
enc = data.encode() # utf-8 by default
print base64.encodestring(enc)
This also works in 2.7 :)
这也适用于 2.7 :)
回答by BrB
Here are two methods worked on python3 encodestringis deprecated and suggested one to use is encodebytes
这里有两种在 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