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.

Answer from dano on Stack Overflow
🌐
Medium
medium.com › personal-work-revision › how-to-decode-base64-encoded-88b2c08ba64c
How to Decode base64 Encoded with Python ? | by Pelin R. Kuran | Personal Work Revision | Medium
October 28, 2020 - In this article we will be trying to decode base64 encoded string object of a JSON file with the great Python also as a bonus I will show how to get your JSON data in a web service. Before starting I…
Discussions

Trying to print out json from a decoded base64 - Python - Stack Overflow
base64.b64decode(str).decode(str) returns a string str. If that string should be json then you can use json.loads to transform the string str to a dict where you can get a single value by it's key. More on stackoverflow.com
🌐 stackoverflow.com
Decode a base64 encoded JSON string generated from JavaScript in Python - Stack Overflow
I'm trying to decode it from Python. I'm doing: >>> import base64 >>> import json >>> json.loads(base64.b64decode("eyLpIjoi6CJ9")) More on stackoverflow.com
🌐 stackoverflow.com
python - extract Json file to decode in base64 - Stack Overflow
with respect, I am trig to use the contents of a json file which is encoded with base64. I would like to decode the encoded part of the json file. More on stackoverflow.com
🌐 stackoverflow.com
December 5, 2016
python 3.x - Serialize in JSON a base64 encoded data - Stack Overflow
The error is yelling that a binary is not JSON serializable. from base64 import b64encode # *binary representation* of the base64 string assert b64encode(b"binary content") == b'YmluYXJ5IGNvbnRlbnQ=' # base64 string assert b64encode(b"binary content").decode('utf-8') == 'YmluYXJ5IGNvbnRlbnQ=' More on stackoverflow.com
🌐 stackoverflow.com
October 8, 2019
Top answer
1 of 3
2

Considering that you have loaded the json data into an object. You can then try the following:

import json
import base64

json_obj = {
    "equno": "229151246954324320",
    "data": "CdwL703m6njjyJ7tdEXdRoYKKv49oatv9UWvdLONpWgd407fakXNfbt18j+qKb/toYgHZvj34ig7iu4XN7BfrqTf/wNsIdVNJ67cH9hCyIfULWLgyT01vQ7u5zS5vSB9hazXTQHRYGxpV+eCrVFMEdxHId54sJDn+KL8hea93WyQKlFwMDO0QQD5X2lK02Y88uI7MehBUFXzK5jNTgKmLtUE9KoM4xF6bEzm2oNMrxz0QwOB4b/tvRvhThb/r+Wgb32gV3UBZBZ/RP4ID+lc7JE7TLVRyeGCNA+uV11/no358XZdGo/E5Aq7KZ95W+rQ8TE3/PLbodAhWZ+1wAcXvfuxJxpIm0giOZv3Dys/pZesM5wbdwaNrFnD+ngHfXB67IxiBM3oRRxC7CBHoFvQFjC8g2E3dk1ELP6VPex24lPJY1JeBwuy8DQroN7rxa4bwLAE6Z3SyL16dpwYdMmAB2YN2h4nMGfl1TMXPGsJKxcSv4tBLj905WTGYgDKG3sQ0AR4YHoPKni7/rUZQb/hM25wXFKYNRzGU6EIleCTP4fl1vqASLFUHDS0GqjwcYkCOilvDbb3PqNqDzPEI84L7XDidiWQ8XKfzw7ryjuIaw1b1ODqN3+ctnny88WXTzANzwA5wjqfhDJDGpHr58fQgi1/j2QIsFBt+VoOslxvx1YQvbubDTwM7dTEwWDY0U5+l8KvSv9fYIMbNYxjwXU3tR2SFhClumNjisUE0lHgCBAfkbTA5Fw9eW3+QRZdB5rY/7DWgxlRnBORZ54c5xxTnsk2ntFm14zQA8HN7zv09FQW+sMk6B767cyzi5HoEkf+PjnNh78OrIPVOFtigMYUb5PdDWDzjDCu2+9dN4mm5aml+/SIOFDUHg6aX+GLj7c0tI0thMFAR6dKP6QtmVbUanF7gSt+L2c4qRq48s3QYMlrTr++PqeoCYNuhWIo2iXllvzERarLDU/pxZNfGB39bFmjmiAnLwmDqNZuVTi40/A38AI+r4f39Y/eywskz/rco1CZGUXxd0FJj0pwdO9H0eedwVgXAmi3KYy3j5MZBWeObqs/ufvRpHjDeh54Bq91DrxcKPya/b6FGDxH73jIgB9Y9x/mbZq2h20H9fbbV+hTk8XIA5ItY+2N9J7FHiJ+NyQbl4UNZT/GVF4HS+NXplgzEAEIlzgRwrNoY0GJzeocxZlAa5f5ANu7OHltqpSTAZ0PzVCopG1NgwaQEpS08mVAtgXo7jq34VejdNuHiTo+/ht3Dn+C+WzKXHZIABkhHjGg1Bv4hJHuLXIpQjIE0xwQo2UcTmcAYvrGO6FcHZz+eRUmJyrtsJczwZK7nimfgJ6T/iuggPVwyn9pifU9VA=="
}

print(base64.b64decode(json_obj["data"]))
2 of 3
1

Here's a way to do that in Python:

import base64
import json
with open("sample_data.json") as f: 
    text = f.read()
    d = json.loads(text)
    data = base64.b64decode(d["data"])

The variable data now contains the decoded content of the relevant item in the json file.

🌐
Johnlekberg
johnlekberg.com › blog › 2020-12-11-stdlib-json.html
Using Python's json module
December 11, 2020 - for server, server_data in data.items(): for i, secret in enumerate(server_data["secrets"]): if isinstance(secret, bytes): server_data["secrets"][i] = base64.b64encode( secret ).decode() elif isinstance(secret, dict) and isinstance( secret.get("value"), bytes ): server_data["secrets"][i][ "value" ] = base64.b64encode(secret["value"]).decode() print(json.dumps(data, indent=2)) { "server-a": { "secrets": [ "yeOd0C/b8FMFmA==", "452YyfBT29AvBQ==" ] }, "server-b": { "secrets": [ "yfBT453QL9sFmA==", { "compromised": "2020-10-01", "value": "yZ2Y0C/bBfBT4w==" } ] } } Instead of doing it manually, use
🌐
Medium
medium.com › @maggi.giuseppe › python-embedding-images-in-json-objects-with-base64-8579059d80d7
Python: embedding images in JSON objects with base64 | by Giuseppe Maggi | Medium
March 12, 2024 - The following code shows how to extract the image we included in the JSON file. Obviously, the code depends on the structure we created for the object. In fact, we get the value of content of the first element in the images list: from io import BytesIO import base64, json from PIL import Image with open('embedded.json', 'r') as f: data_received=json.load(f) im = Image.open(BytesIO(base64.b64decode(data_received['images'][0]['content']))) im.save('picture_out.jpg', 'JPEG')
Top answer
1 of 3
1

You are passing in your whole list, which itself contains more lists:

>>> response_i['objcontent'][0]['rowvalues']
[['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAA8D8=', '7HitYA'], ['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAACEA=', '7HitYA'], ['AAAAAAAALkA=', 'AAAAAADgU8A=', 'AAAAAAAAFEA=', '7HitYA']]

You'd need to decode each separate entry, not the whole list:

for response_i in response['response']:
    for row in response_i['objcontent'][0]['rowvalues']:
        for encoded_obj in row[:-1]:
            decoded = base64.b64decode(encoded_obj)

Note that I ignore the last value in the row, that's not a Base64 value.

Your next problem is that your Base64 data doesn't contain enough bytes to hold 12 float values (each 8 bytes, so you'd need 96 bytes). Since they are 8 bytes each, you probably have just one floating point value in each string.

So you'd want to decode just the one float:

floating_point_value = struct.unpack('d', decoded)[0]

Demo:

>>> for response_i in response['response']:
...     for row in response_i['objcontent'][0]['rowvalues']:
...         for encoded_obj in row[:-1]:
...             decoded = base64.b64decode(encoded_obj)
...             print(struct.unpack('d', decoded)[0])
...
15.0
-79.5
1.0
15.0
-79.5
3.0
15.0
-79.5
5.0
2 of 3
0

Your json seems to be malformed, there are more opening [ than closing ]. So I can't give you an exact breakdown.

In any event, the value that matches the key 'rowvalues' is a list of lists [ [], [], [] ]. So you need to break it down accordingly to pass the correct values to the decoder

for value_list in response_i['objcontent'][0]['rowvalues']:
    for value in value_list:
        # enter your decode code here
Find elsewhere
Top answer
1 of 3
144

You must be careful about the datatypes.

If you read a binary image, you get bytes. If you encode these bytes in base64, you get ... bytes again! (see documentation on b64encode)

json can't handle raw bytes, that's why you get the error.

I have just written some example, with comments, I hope it helps:

from base64 import b64encode
from json import dumps

ENCODING = 'utf-8'
IMAGE_NAME = 'spam.jpg'
JSON_NAME = 'output.json'

# first: reading the binary stuff
# note the 'rb' flag
# result: bytes
with open(IMAGE_NAME, 'rb') as open_file:
    byte_content = open_file.read()

# second: base64 encode read data
# result: bytes (again)
base64_bytes = b64encode(byte_content)

# third: decode these bytes to text
# result: string (in utf-8)
base64_string = base64_bytes.decode(ENCODING)

# optional: doing stuff with the data
# result here: some dict
raw_data = {IMAGE_NAME: base64_string}

# now: encoding the data to json
# result: string
json_data = dumps(raw_data, indent=2)

# finally: writing the json string to disk
# note the 'w' flag, no 'b' needed as we deal with text here
with open(JSON_NAME, 'w') as another_open_file:
    another_open_file.write(json_data)
2 of 3
13

Alternative solution would be encoding stuff on the fly with a custom encoder:

import json
from base64 import b64encode

class Base64Encoder(json.JSONEncoder):
    # pylint: disable=method-hidden
    def default(self, o):
        if isinstance(o, bytes):
            return b64encode(o).decode()
        return json.JSONEncoder.default(self, o)

Having that defined you can do:

m = {'key': b'\x9c\x13\xff\x00'}
json.dumps(m, cls=Base64Encoder)

It will produce:

'{"key": "nBP/AA=="}'
🌐
Code Beautify
codebeautify.org › base64-to-json-converter
Base64 to JSON Converter to convert Base64 Encoded data to JSON String.
Converts Base64 string into JSON data. It's easy to use this decoder to decode JSON data.
🌐
Elastic
discuss.elastic.co › elastic stack › logstash
Base64 decoding & decompression of json - Logstash - Discuss the Elastic Stack
August 4, 2021 - I have a JSON input containing a [message][message_json] field which is compressed & base64 encoded at the source. This is the python code used to decode, decompress, and deserialize the field: message['message_json'] = json.loads(zlib.decompress(base64.b64decode(message['message_json']), 15 + 32)) How can I replicate the same using logstash filter?
🌐
GeeksforGeeks
geeksforgeeks.org › base64-to-json-converter
Base64 to JSON Converter | GeeksforGeeks
March 15, 2024 - Both these formats are used to represent the data in various scenarios, We can convert the YAML to JSON format by using a mixture of Python Library and Shell Script for automation. We ... There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format.
🌐
DEV Community
dev.to › tooldeck › base64-decode-in-python-complete-guide-b64decode-urlsafe-padding-fix-3ph7
Base64 Decode in Python — Complete Guide (b64decode, urlsafe, padding fix) - DEV Community
March 25, 2026 - import base64, json from pathlib import Path def decode_attachment(envelope_path: str, output_path: str) -> None: """ Read a JSON envelope with a Base64-encoded attachment, decode it, and write the binary output to disk.
🌐
iO Flood
ioflood.com › blog › python-base64-encode
Python Base64 Encode | b64encode() Function Guide
February 1, 2024 - We then convert the JSON object to a string using the dumps() function from the json module. This string is then converted to bytes and passed to the b64encode() function to be encoded. As you can see, base64 encoding in Python is quite flexible and can handle a variety of data types.
🌐
Medium
medium.com › @ume.cooray › understanding-base64-encoding-in-python-5b31f23dd007
Understanding Base64 Encoding and Decoding in Python | by Umayangana Cooray | Medium
March 18, 2025 - To reverse the encoding, use base64.b64decode() on the Base64 string to get back the original byte data. ... Finally, decode the bytes back into a UTF-8 string to retrieve the original content. Data Transmission: Ensures data stays intact during transport over text-based systems.
🌐
JSONLint
jsonlint.com › json-base64
JSON Base64 Encode/Decode - Convert JSON to Base64 | JSONLint | JSONLint
# Encode echo '{"name":"John"}' | base64 # Decode echo 'eyJuYW1lIjoiSm9obiJ9' | base64 -d · Standard Base64 uses + and / characters, which have special meaning in URLs. URL-safe Base64 replaces these with - and _. Encoding twice — If your JSON is already Base64, encoding again creates double-encoding issues
🌐
Stack Overflow
stackoverflow.com › questions › 68025949 › python-and-bas64-encoding
json - python and bas64 encoding - Stack Overflow
>>> base64.b64decode(b'dGVzdCBzdHJpbmc=') b'test string' >>> base64.b64decode(b'dGVzdCBzdHJpbmc=').decode("utf-8") 'test string' ... Sign up to request clarification or add additional context in comments. ... You have highlighted my problem. The value of the string is already encoded as base64 but the python type after loading the json is str.