Convert byte string to base64 encoded string (non-byte string output)

I was wondering if it is possible to convert the byte string that I received from reading the file to a string (like type(output) == str ). Everything I found on Google so far has been answers such as How do you encode a base-64 PNG image for use in the data-uri in a CSS file? which seems to work in python 2 (where, if I'm not mistaken, the strings were byte strings anyway), but which no longer works in python 3.4.

The reason I want to convert this received byte string to a regular string is because I want to use data with a 64-encoded data base to store in a JSON object, but I keep getting an error similar to:

 TypeError: b'Zm9v' is not JSON serializable 

Here is 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 preserving base64 encoding (so in this example I want the result to be ["Zm9v"] Is this possible?

+5
source share
1 answer

Try

 data = b'foo'.decode('UTF-8') 

instead

 data = b'foo' 

to convert it to a string.

+6
source

Source: https://habr.com/ru/post/1234226/


All Articles