The JSON object must be str, bytes or bytearray, not dict

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
9 min

banner

# Table of Contents

  1. The JSON object must be str, bytes or bytearray, not DICT
  2. The JSON object must be str or bytes not TextIOWrapper
  3. The JSON object must be str, bytes or bytearray, not LIST
  4. The JSON object must be str, bytes or bytearray not RESPONSE

Make sure to click on the correct subheading depending on your error message

# The JSON object must be str, bytes or bytearray, not dict

The Python "TypeError: the JSON object must be str, bytes or bytearray, not dict" occurs when we pass a dictionary 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 dict to a JSON string.

typeerror the json object must be str bytes or bytearray not dict

Here is an example of how the error occurs.

main.py
import json my_dict = {'name': 'Bobby Hadz', 'age': 30} # โ›”๏ธ TypeError: the JSON object must be str, bytes or bytearray, not dict result = json.loads(my_dict)

The json.loads method parses a JSON string into a native Python object.

Since we already have a native Python object (a dictionary), we can't pass it to the json.loads() method.

# Converting a dictionary to a JSON string

If you need to convert a dictionary to a JSON string, use the json.dumps() method.

main.py
import json my_dict = {'name': 'Bobby Hadz', 'age': 30} my_json_str = json.dumps(my_dict) print(my_json_str) # ๐Ÿ‘‰๏ธ '{"name": "Bobby Hadz", "age": 30}' 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.

# Converting a JSON string to a native Python object

If you need to convert a Python object to a JSON string, you have to use the json.dumps() method.

main.py
import json json_str = r'{"name": "Alice", "age": 30}' # โœ… Parse JSON string to a Python native dict my_dict = json.loads(json_str) print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> # โœ… Convert Python native dict to a JSON string my_json_str = json.dumps(my_dict) print(type(my_json_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

The json.loads() method helps us load a Python native object (e.g. a dictionary or a list) from a JSON string.

# Using the json.load method to read from a JSON file

If you need to read from a JSON file, use the json.load() method.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} print(my_data['name']) # ๐Ÿ‘‰๏ธ 'Alice' print(type(my_data)) # ๐Ÿ‘‰๏ธ <class 'dict'>

The code sample above assumes that you have an example.json file in the same directory.

example.json
{"name": "Alice", "age": 30}

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.

Here is the equivalent example if you use the open() function without the with statement.

main.py
import json file_name = 'example.json' json_file = open(file_name, 'r', encoding='utf-8') json_data = json.load(json_file) print(json_data) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} print(json_data['name']) # ๐Ÿ‘‰๏ธ 'Alice' print(type(json_data)) # ๐Ÿ‘‰๏ธ <class 'dict'> json_file.close()

The code sample achieves the same result but uses the open() function without the with statement.

The with statement takes care of automatically closing the file for us, but when using the open() function directly, we have to close the file manually.

# You can convert the following Python objects to JSON

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> print(isinstance(my_dict, dict)) # ๐Ÿ‘‰๏ธ True my_str = 'hello world' 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.

# Table of Contents

  1. The JSON object must be str or bytes not TextIOWrapper
  2. The JSON object must be str, bytes or bytearray, not LIST
  3. The JSON object must be str, bytes or bytearray not RESPONSE

# The JSON object must be str or bytes not TextIOWrapper

The Python "TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper" occurs when we pass a file object to the json.loads() method.

To solve the error, pass the file object to the json.load() method instead.

shell
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 7, in <module> my_data = json.loads(f) ^^^^^^^^^^^^^ File "/usr/lib/python3.11/json/__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

Here is an example of how the error occurs.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: # โ›”๏ธ TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper my_data = json.loads(f)

# Using the json.load() method to deserialize a JSON file

We can't pass a file object directly to the json.loads() method, but we can use the json.load() method to deserialize a file to a Python object.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} print(type(my_data)) # ๐Ÿ‘‰๏ธ <class 'dict'>

The code sample assumes that you have an example.json file in the same directory.

example.json
{"name": "Alice", "age": 30}

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.

# Manually calling the file.read() method with json.loads()

Alternatively, you manually call the read() method on the file object and use the json.loads() method.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: # ๐Ÿ‘‡๏ธ make sure to call read() my_data = json.loads(f.read()) print(my_data) # ๐Ÿ‘‰๏ธ {'name': 'Alice', 'age': 30} print(type(my_data)) # ๐Ÿ‘‰๏ธ <class 'dict'>

The example above achieves the same result.

However, instead of relying on the json.load() method to call read() on the file object for us, we manually do it and use the json.loads() method instead.

If you need to parse a JSON string into a native Python object, you have to use the json.loads() method.

if you need to convert a Python object to a JSON string, you have to use the json.dumps() method.

main.py
import json json_str = r'{"name": "Alice", "age": 30}' # โœ… Parse JSON string to Python native dict my_dict = json.loads(json_str) print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> # โœ… Convert Python native dict to a JSON string my_json_str = json.dumps(my_dict) print(type(my_json_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

The json.loads() method basically helps us load a Python native object (e.g. a dictionary or a list) from a JSON string.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

# Checking what type a variable stores

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> print(isinstance(my_dict, dict)) # ๐Ÿ‘‰๏ธ True my_str = 'hello world' 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.

# Table of Contents

  1. The JSON object must be str, bytes or bytearray, not LIST
  2. The JSON object must be str, bytes or bytearray not RESPONSE

# The JSON object must be str, bytes or bytearray, not list

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.

typeerror the json object-must-be-str-bytes-or-bytearray-not-list

Here is an example of how the error occurs.

main.py
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.

Since we already have a native Python object (a list), we can't pass it to the json.loads() method.

# Converting the list to a JSON string

If you need to convert a list to a JSON string, use the json.dumps() method.

main.py
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.

If you need to parse a JSON string to a native Python object, you have to use the json.loads() method.

If you need to convert a Python object to a JSON string, you have to use the json.dumps() method.

main.py
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.

# Reading a list from a JSON file

If you need to read from a JSON file, use the json.load() method.

main.py
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.

example.json
["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.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

# Checking the type of a variable

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
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.

# The JSON object must be str, bytes or bytearray not Response

The Python "TypeError: the JSON object must be str, bytes or bytearray, not Response" occurs when we pass a Response object to the json.loads() method.

To solve the error, call the json() method on the Response object instead, e.g. result = res.json().

typeerror the json object must be str bytes or bytearray not response

Here is an example of how the error occurs.

main.py
import json import requests def make_request(): res = requests.get('https://reqres.in/api/users') # โ›”๏ธ TypeError: the JSON object must be str, bytes or bytearray, not Response parsed = json.loads(res) make_request()

We passed a Response object to the json.loads() method which caused the error.

# Use the json() method to parse the response

To solve the error, use the json() method on the response object instead.

main.py
import requests def make_request(): res = requests.get('https://reqres.in/api/users') # โœ… call .json() method on Response object parsed = res.json() print(parsed) print(type(parsed)) # ๐Ÿ‘‰๏ธ <class 'dict'> make_request()
We called the json() method on the Response object to parse it into a native Python object before accessing any of its keys.

You should use the json() method to parse the data from all requests, not just HTTP GET.

# Making an HTTP Post request with the requests module

Here is an example of a POST request with the requests module.

main.py
import requests def make_request(): res = requests.post( 'https://reqres.in/api/users', data={'name': 'John Smith', 'job': 'manager'} ) # โœ… Parse the JSON response to native Python object data = res.json() # ๐Ÿ‘‡๏ธ {'name': 'John Smith', 'job': 'manager', 'id': '649', 'createdAt': '2022-05-20T10:11:23.939Z'} print(data) print(data['name']) # ๐Ÿ‘‰๏ธ "John Smith" print(data['job']) # ๐Ÿ‘‰๏ธ "manager" print(data['id']) # 649 make_request()

If you are working with a JSON string or a native Python object, make sure to use the json.loads() and json.dumps() methods.

If you need to parse a JSON string to a native Python object, you have to use the json.loads() method.

If you need to convert a Python object into a JSON string, you have to use the json.dumps() method.

main.py
import json json_str = r'{"name": "Alice", "age": 30}' # โœ… Parse the JSON string to Python native dict my_dict = json.loads(json_str) print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> # โœ… Convert the Python native dict to a JSON string my_json_str = json.dumps(my_dict) print(type(my_json_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

The json.loads() method basically helps us load a Python native object (e.g. a dictionary or a list) from a JSON string.

The json.dumps() method converts a Python object to a JSON formatted string.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

# Checking the type of a variable

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'> print(isinstance(my_dict, dict)) # ๐Ÿ‘‰๏ธ True my_str = 'hello world' 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.

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.

Copyright ยฉ 2024 Borislav Hadzhiev