Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base 64 encode a JSON variable in Python

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

like image 587
AshKsh Avatar asked Jul 18 '14 18:07

AshKsh


People also ask

Can you Base64 encode JSON?

World's simplest base64 JSON encoder for web developers and programmers. Just paste your JSON data structure in the form below, press Base64 Encode JSON button, and you get a base64-encoded JSON document.

How do I encode Base64 in Python?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do you decode a base 64 in python?

Base64 Decoding an Image To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.


1 Answers

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.

like image 200
dano Avatar answered Oct 12 '22 23:10

dano