Base 64 encode a JSON variable in Python
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:
>>> 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.
You could encode the string first, as UTF-8 for example, then base64 encode it:
data = '{"hello": "world"}'enc = data.encode() # utf-8 by defaultprint base64.encodestring(enc)
This also works in 2.7 :)
Here are two methods worked on python3encodestring is deprecated and suggested one to use is encodebytes
import jsonimport base64with 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