(JSON) TypeError: a bytes-like object is required, not 'str'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

(JSON) TypeError: a bytes-like object is required, not 'str' #

To solve the Python JSON "TypeError: a bytes-like object is required, not 'str'", make sure to open the JSON file in w mode and not wb mode when writing strings to a file.

json bytes like object is required not str

Here is an example of how the error occurs.

main.py
import json my_json = json.dumps({'name': 'Alice', 'age': 30}) file_name = 'example.json' # 👇️ opened file in wb mode with open(file_name, 'wb') as f: # ⛔️ TypeError: a bytes-like object is required, not 'str' f.write(my_json)

We opened the file in wb (binary) mode rather than w (text) mode which caused the error.

To solve the error, use the w mode when writing to a JSON file.

main.py
import json my_json = json.dumps({'name': 'Alice', 'age': 30}) file_name = 'example.json' # ✅ opened file in w mode and set encoding to utf-8 with open(file_name, 'w', encoding='utf-8') as f: f.write(my_json)

We opened the JSON file in w (text) mode.

When a file is opened in text mode, we read and write strings from and to the file.

Those strings are encoded using a specific encoding (utf-8 in the example).

Note that if you don't explicitly set the encoding keyword argument, the default is platform-dependent.

If you want to both read from and write to the file, use the r+ mode when opening it.

If you append a b to the mode (like in the first code snippet), the file is opened in binary mode.

Note that you cannot specify encoding when opening a file in binary mode.

When a file is opened in binary mode, data is read and written as bytes objects.

This means that you could encode your JSON string to a bytes object using the encode() method if you have the wb mode set.

main.py
import json my_json = json.dumps({'name': 'Alice', 'age': 30}) file_name = 'example.json' with open(file_name, 'wb') as f: f.write(my_json.encode('utf-8'))

The str.encode method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

However, it is much simpler to open the JSON file in w (or another text) mode, so you can write strings directly.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.