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 › @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 - As shown, we shortened the encoded string in the content property to make the representation more concise. 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')
Discussions

azure functions - base64 to json property in Python - Stack Overflow
encoded = base64.b64encode(data).decode() will give you back a string which will normally parse (b64encode - encode as b64 in bytes object, decode - change bytes object to str). Because b64 is ASCII it can be freely converted from bytes to str (unicode) and back ... You might also consider specifying the encoding type as an option if it is not UTF-8. ... If it is image which you want to send as http reponse you shouldn't be doing json... 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")) ... Note: I'm using base64 encoding so this can be safely passed as an URL query string parameter. More on stackoverflow.com
🌐 stackoverflow.com
python decoding base64 into a json file - Stack Overflow
So I tried to compress a JSON file and decompress it using this code (the two built function) the compressing process works fine, but I can't figure out how to decompress it back to JSON, so I can ... More on stackoverflow.com
🌐 stackoverflow.com
May 19, 2020
How can I get python base64 encoding to play nice with json? - Stack Overflow
I have large binary zip files to transport as part of a JSON interface. I've converted them to base64 for this purpose but I'm unable to read them back cleanly as shown with a simple case here: ~ $ More on stackoverflow.com
🌐 stackoverflow.com
May 2, 2013
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=="}'
🌐
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 - Why Python is So Popular? published by Programming with Mosh. So, if you are ready let’s start decoding! ... After installing the modules and adjusting necessary things you should be able to import all the followings. Now if your JSON is on your computer, you need to get it.
🌐
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.
🌐
ProgramCreek
programcreek.com › python › example › 262 › base64.b64encode
Python Examples of base64.b64encode
def lan_event(self): '''变更语言的方法''' #读取本地配置文件 num = 0 with open(".\data.ini",'rb') as f: self.lan_data = f.readlines() with open(".\data.ini",'wb') as f: for line in self.lan_data: if num == self.dual_host_view.currentRow() + 1: data = base64.b64decode(line) data = json.loads(data.decode()) data['lan'] = self.lan_input.currentIndex() f.write(base64.b64encode(json.dumps(data).encode())) f.write('\n'.encode()) else: f.write(line) num += 1 a = QMessageBox() #写入成功提示 a.information(a,self.tr("Success"),self.tr("Language will be changed after resrart the application")) Example #8 ·
Find elsewhere
🌐
Johnlekberg
johnlekberg.com › blog › 2020-12-11-stdlib-json.html
Using Python's json module
December 11, 2020 - TypeError: Object of type datetime is not JSON serializable · You could manually encode the data. E.g., import base64 data = b"\xc9\xe3\x9d\xd0/\xdb\xf0S\x05\x98" data = base64.b64encode(data).decode() json.dumps(data) '"yeOd0C/b8FMFmA=="' data = datetime.datetime(2019, 6, 17, 3, 46, 23) data = data.isoformat() json.dumps(data) '"2019-06-17T03:46:23"' But, what if the data that you need to encode is embedded inside other data?
Top answer
1 of 1
2

according to your code:

>>> compressed_json = data['base64(zip(o))']
>>> decompressed_json = zlib.decompress(b64decode(compressed))
>>> decompressed_json
b'"C:\\\\Users\\\\Beeri\\\\Google Drive\\\\Finance\\\\BPicks\\\\Stock Info\\\\daily data copy - Copy\\\\A.json"'
>>> json.loads(decompressed_json)
'C:\\Users\\Beeri\\Google Drive\\Finance\\BPicks\\Stock Info\\daily data copy - Copy\\A.json'

As mentioned by Karl, you basically compressed the file path not the actual file: try this

import zlib, json
from base64 import b64encode, b64decode

path = r"filename.json"

def compress_json(data):
    return {'base64(zip(o))': b64encode(zlib.compress(json.dumps(data).encode('utf-8'))).decode()}

def decompress_json(data):
    compressed_json =  data['base64(zip(o))']
    return json.loads(zlib.decompress(b64decode(compressed_json)))

with open(path, "r") as f:
    data = f.read()
    compressed_json = compress_json(data)
    print(compressed_json)
    """
    {'base64(zip(o))': 'eJxTio7JUwCCaggFAjFKKYklqTFKVkCWkYGRga6Bqa6hhYKhmZW
    BARDFKOkgq80vSM0DqbUw1jO3RJHJyS+HSpiZo0hkZKZnYNeSnJNfnIpdU1l+TmkuWM7QwtT
    U0sQMIlmrQ7T7Ta1MLfG638LQFIcHzHF6wMIYpwfQ/IbsASMjEzNLcjxggdcDuMLf3AKX83EH
    P3pgIDvfwBgYBVDnx+TFKgEASGiHCQ=='}
    """
    decompressed_json = decompress_json(compressed_json)
    print(decompressed_json)
    """
[
    {
        "date": "2020-05-18 16:00:00",
        "open": 83.79,
        "low": 83.67,
        "high": 83.79,
        "close": 83.67,
        "volume": 1855946
    },
    {
        "date": "2020-05-18 15:59:00",
        "open": 83.815,
        "low": 83.77,
        "high": 83.83,
        "close": 83.79,
        "volume": 1822469
    },
    {
        "date": "2020-05-18 15:58:00",
        "open": 83.9,
        "low": 83.78,
        "high": 83.9,
        "close": 83.815,
        "volume": 1803855
    }
]
"""
🌐
GitHub
github.com › ssheftel › img2b64
GitHub - ssheftel/img2b64: store images in json documents using base64 encoding · GitHub
img2b64.py will convert all jpg and png in the directory into base64 encoded strings and save them in a single file named base64imgs.json. Optionally the directory in which to to write the base64imgs.json file can be specified by passing the output directory path as the 2nd argument. For example: python img2b64.py /Users/sam/SomeDir /Users/sam/SomeOtherDir
Author: ssheftel
🌐
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 - Let’s walk through the following Python script to understand the process: import base64 import json # Example JSON token (as a string) json_token = "" # Step 1: Convert the JSON string to bytes json_bytes = json_token.encode('utf-8') # Step ...
🌐
GitHub
github.com › openlabs › docker-wkhtmltopdf-aas › issues › 9
JSON example does not work in Python3 due to encoding differences · Issue #9 · openlabs/docker-wkhtmltopdf-aas
May 4, 2015 - In Python3 encoding to base64 is done with base64.b64encode which creates a bytes object. Json.dumps only takes a string, so the example produces an error. Attempting to read the file as utf-8 doesn't produce an error, but the resulting ...
Author: openlabs
🌐
Stack Overflow
stackoverflow.com › questions › 70612284 › how-to-base64-encode-a-python-array-not-double-encode-it
json - How to base64 encode a python array, not double-encode it? - Stack Overflow
# based on https://websockets.readthedocs.io/en/9.0.1/intro.html import asyncio import json from base64 import b64encode, b64decode import array myarray = array.array('H', [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) class Base64Encoder(json.JSONEncoder): # ssubotin, https://stackoverflow.com/questions/37225035/serialize-in-json-a-base64-encoded-data def default(self, o): if isinstance(o, bytes): return b64encode(o).decode() return json.JSONEncoder.default(self, o) # array_event() creates a message which will be sent over websocket def array_event(): bytextnd = bytearray() for x in range(len(myar
🌐
GeeksforGeeks
geeksforgeeks.org › encoding-and-decoding-base64-strings-in-python
Encoding and Decoding Base64 Strings in Python - GeeksforGeeks
August 7, 2024 - With the help of base64.encodestring(s) method, we can encode the string using base64 encoded data into the binary form. Syntax : base64.encodestring(string) Return : Return the encoded string.
🌐
Stack Overflow
stackoverflow.com › questions › 68025949 › python-and-bas64-encoding
json - python and bas64 encoding - Stack Overflow
you can use .encode() and .decode() to convert strings · >>> import base64 >>> s = "test string" >>> base64.b64encode(s.encode()) b'dGVzdCBzdHJpbmc='
🌐
DEV Community
dev.to › tooldeck › base64-encode-in-python-complete-guide-b64encode-urlsafe-jwt-files-14la
Base64 Encode in Python — Complete Guide (b64encode, urlsafe, JWT, files) - DEV Community
April 2, 2026 - When the encoded value appears in a URL, a filename, or a cookie, you need the URL-safe variant: urlsafe_b64encode() substitutes - for + and _ for /. JWTs use URL-safe Base64 without padding for all three segments (header, payload, signature). The padding must be stripped manually — Python's stdlib keeps it. import base64 import json def encode_jwt_segment(data: dict) -> str: """Encode a dict as a URL-safe Base64 string without padding (JWT format).""" json_bytes = json.dumps(data, separators=(",", ":")).encode("utf-8") return base64.urlsafe_b64encode(json_bytes).rstrip(b"=").decode("ascii")
🌐
Base64
base64.dev › home › articles › binary data in json
Binary Data in JSON: Base64 Encoding — base64.dev
July 3, 2026 - JSON strings must be valid Unicode. Embedding raw bytes — or even Latin-1 "binary-as-text" — risks data corruption the moment the payload passes through a parser, a database column with a different encoding, or a logging pipeline that normalizes text.
🌐
GitHub
gist.github.com › khornberg › b87e4a72532a342e1e5ebb16b5739e8f
python 3 base64 encode dict · GitHub
python 3 base64 encode dict · Raw · encode_decode_dictionary.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.