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 - For each image, we have a JSON document with several attributes such as timestamp, author, collection_name and content, this one containing the base64 encoded image. To run the code, we need the Pillow library that can be installed with: ... This isn’t the only way to encode an image in base64 but it’s the one we chose.
Discussions

python 3.x - Serialize in JSON a base64 encoded data - Stack Overflow
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: More on stackoverflow.com
🌐 stackoverflow.com
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
JSON example does not work in Python3 due to encoding differences
Attempting to read the file as ... wkhtmltopdf is expecting a base64 encoded HTML string? Also giving it the --encoding utf-8 option still produces a garbled PDF. Basically I can't figure out how to get the JSON API working in Python3.... More on github.com
🌐 github.com
5
May 4, 2015
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
🌐
iO Flood
ioflood.com › blog › python-base64-encode
Python Base64 Encode | b64encode() Function Guide
February 1, 2024 - In this example, we first define a JSON object. 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.
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=="}'
🌐
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 ·
🌐
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.
Find elsewhere
🌐
Johnlekberg
johnlekberg.com › blog › 2020-12-11-stdlib-json.html
Using Python's json module
December 11, 2020 - def custom_decoder(x): if x.get("type") == "datetime": return datetime.datetime.fromisoformat(x["value"]) elif x.get("type") == "bytes": return base64.b64decode(x["value"].encode()) else: return x json.loads(document, object_hook=custom_decoder)
🌐
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.
🌐
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
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.
🌐
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
🌐
Base64
base64.dev › home › articles › binary data in json
Binary Data in JSON: Base64 Encoding — base64.dev
July 3, 2026 - How to embed binary data in JSON using Base64. Size tradeoffs, code examples in JavaScript and Python, and multipart alternatives.
🌐
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 - 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, ...
🌐
GitHub
github.com › ssheftel › img2b64
GitHub - ssheftel/img2b64: store images in json documents using base64 encoding · GitHub
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
🌐
Python
docs.python.org › 3 › library › base64.html
base64 — Base16, Base32, Base64, Base85 Data Encodings
The legacy interface does not support decoding from strings, but it does provide functions for encoding and decoding to and from file objects. It only supports the Base64 standard alphabet, and it adds newlines every 76 characters as per RFC 2045.
🌐
DEV Community
dev.to › tooleroid › base64-encoding-in-python-simplified-guide-examples-nan
Base64 Encoding in Python: Simplified Guide & Examples - DEV Community
December 16, 2024 - def safe_encode_decode(text: str) -> tuple[str, str]: try: encoded = base64.b64encode(text.encode()).decode() decoded = base64.b64decode(encoded).decode() return encoded, decoded except UnicodeEncodeError: print("Error: Unable to encode text") ...
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
    }
]
"""
🌐
JSON Formatter
jsonformatter.org › json-to-base64
JSON to Base64 Converter : Best and Free
Online JSON to Base64 converter to convert JSON data to Base64 encoded string.
🌐
Code Beautify
codebeautify.org › json-to-base64-converter
JSON to Base64 Converter to convert JSON data to Base64 String.
Converts JSON data into Base64 String. It's easy to use JSON to Base64 encoder which helps to encode JSON String.