Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Mert Kahveci
The Python "TypeError: the JSON object must be str, bytes or bytearray, not
list" occurs when we pass a list to the json.loads()
method. To solve the
error, remove the call to json.loads()
and use the json.dumps()
method if
trying to convert the list to a JSON string.
Here is an example of how the error occurs.
import json my_list = ['Alice', 'Bob', 'Carl'] # ⛔️ TypeError: the JSON object must be str, bytes or bytearray, not list result = json.loads(my_list)
The json.loads method parses a JSON string into a native Python object.
json.loads()
method.If you need to convert a list to a JSON string, use the json.dumps()
method.
import json my_list = ['Alice', 'Bob', 'Carl'] my_json_str = json.dumps(my_list) print(my_json_str) # 👉️ '["Alice", "Bob", "Carl"]' print(type(my_json_str)) # 👉️ <class 'str'>
The json.dumps method converts a Python object to a JSON formatted string.
In other words, if you need to parse a JSON string into a native Python object,
you have to use the json.loads()
method, and if you need to convert a Python
object into a JSON string, you have to use the json.dumps()
method.
import json json_str = r'["Alice", "Bob", "Carl"]' my_list = json.loads(json_str) print(type(my_list)) # 👉️ <class 'list'> my_json_str = json.dumps(my_list) print(type(my_json_str)) # 👉️ <class 'str'>
The json.loads()
method basically helps us load a Python native object (e.g. a
list or a dictionary) from a JSON string.
If you need to read from a json file, use the json.load()
method.
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # 👉️ ['Alice', 'Bob', 'Carl'] print(my_data[0]) # 👉️ 'Alice' print(type(my_data)) # 👉️ <class 'list'>
The code sample above assumes that you have an example.json
file in the same
directory.
["Alice", "Bob", "Carl"]
The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.
The json.load()
method expects a text file or a binary file containing a JSON
document that implements a .read()
method.
The JSONEncoder
class supports the following objects and types by default.
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int and float derived Enums | number |
True | true |
False | false |
None | null |
If you aren't sure what type of object a variable stores, use the built-in
type()
class.
my_list = ['a', 'b', 'c'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.