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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:17:51  来源:igfitidea点击:

Base 64 encode a JSON variable in Python

pythonjsonpython-3.xbase64

提问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 strobject to a bytesobject for base64to be able to encode them. You can do that using the str.encodemethod:

在 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 base64module, 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