24

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??

0

5 Answers 5

46

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.

Sign up to request clarification or add additional context in comments.

4 Comments

My apologies if my question is ambiguous. actually I am trying to construct a JWS and encode it in Base64. So my variable is like this, header = {"alg": "ES256"}. What I am try to do is base64.b64encode(header).
the only solution I found it work to transform an already string but encoded in base64 to plain text string. Thanks!
Have to import base64 first
@greg Thanks, fixed.
3

You could encode the string first, as UTF-8 for example, then base64 encode it:

data = '{"hello": "world"}'
enc = data.encode()  # utf-8 by default
print base64.encodestring(enc)

This also works in 2.7 :)

Comments

3

Here are two methods worked on python3 encodestring is deprecated and suggested one to use is 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

Comments

2

Here's a function that you can feed a string and it will output a base64 string.

import base64
def b64EncodeString(msg):
    msg_bytes = msg.encode('ascii')
    base64_bytes = base64.b64encode(msg_bytes)
    return base64_bytes.decode('ascii')

Comments

0

Quickest way:

import base64, json
print(base64.b64encode(open("key.json","rb").read()).decode())

Just don't call your file base64.py, I just had that problem, then your base64.py overshadows the lib base64 and you'll get:
AttributeError: partially initialized module 'base64' has no attribute 'b64encode' (most likely due to a circular import)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.