将字节字符串转换为base64编码的字符串(输出不是字节字符串) [英] Convert byte string to base64-encoded string (output not being a byte string)
问题描述
我想知道是否可以将读取文件时得到的字节字符串转换为字符串(因此type(output) == str
).到目前为止,我在Google上发现的所有答案都是您如何基于base-64编码PNG图片以用于data-uri ,这似乎可以在python 2中使用(如果我没记错的话,字符串无论如何都是字节字符串),但是在python 3.4中不再起作用. >
我想将此结果字节字符串转换为普通字符串的原因是,我想使用此base64编码的数据存储在JSON对象中,但我不断收到类似于以下内容的错误:
TypeError: b'Zm9v' is not JSON serializable
这是出现错误的最小示例:
import base64
import json
data = b'foo'
myObj = [base64.b64encode(data)]
json_str = json.dumps(myObj)
所以我的问题是:有一种方法可以将bytes
类型的对象转换为str
类型的对象,同时仍保持base64编码(因此,在此示例中,我希望结果为
尝试
data = b'foo'.decode('UTF-8')
代替
data = b'foo'
将其转换为字符串.
I was wondering if it is possible to convert a byte string which I got from reading a file to a string (so type(output) == str
). All I've found on Google so far has been answers like How do you base-64 encode a PNG image for use in a data-uri in a CSS file?, which does seem like it would work in python 2 (where, if I'm not mistaken, strings were byte strings anyway), but which doesn't work in python 3.4 anymore.
The reason I want to convert this resulting byte string to a normal string is that I want to use this base64-encoded data to store in a JSON object, but I keep getting an error similar to:
TypeError: b'Zm9v' is not JSON serializable
Here's a minimal example of where it goes wrong:
import base64
import json
data = b'foo'
myObj = [base64.b64encode(data)]
json_str = json.dumps(myObj)
So my question is: is there a way to convert this object of type bytes
to an object of type str
while still keeping the base64-encoding (so in this example, I want the result to be ["Zm9v"]
. Is this possible?
Try
data = b'foo'.decode('UTF-8')
instead of
data = b'foo'
to convert it into a string.
这篇关于将字节字符串转换为base64编码的字符串(输出不是字节字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!