Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
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.
Here is an example of how the error occurs.
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.
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).
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.
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.
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.