Skip to main content

How to Resolve Python TypeError: "the JSON object must be str, bytes or bytearray"

The TypeError: the JSON object must be str, bytes or bytearray, not <type> is a common error when working with the json module in Python. It arises when you incorrectly pass an object (like a dictionary, list, file object, or HTTP response) to the json.loads() function, which expects a JSON string, bytes, or bytearray.

This guide explains why this error occurs for different types and provides the correct solutions.

Understanding json.loads() and the TypeError

The json.loads() function is specifically designed to parse (deserialize) a JSON formatted string, bytes object, or bytearray into a corresponding Python object (like a dictionary or list).

The TypeError occurs because you are passing an object that is already a Python object (like a dict, list, file object TextIOWrapper, or requests.Response) to json.loads(). It doesn't know how to "load" these types because they aren't JSON strings or bytes.

Error: ... not dict

Cause & Solution

This happens when you pass a Python dictionary directly to json.loads().

# Error Example
import json
my_dict = {'name': 'Tom Nolan', 'age': 30}
try:
# ⛔️ TypeError: the JSON object must be str, bytes or bytearray, not dict
result = json.loads(my_dict)
except TypeError as e:
print(e)

Solution: If you have a dictionary, you likely don't need json.loads(). If you intend to convert the dictionary to a JSON string, use json.dumps().

Converting Dictionaries to JSON Strings (json.dumps())

# Correct Usage
import json
my_dict = {'name': 'Tom Nolan', 'age': 30}
my_json_str = json.dumps(my_dict) # Convert dict to JSON string
print(my_json_str) # Output: {"name": "Tom Nolan", "age": 30}
print(type(my_json_str)) # Output: <class 'str'>

Error: ... not list

Cause & Solution

This occurs when you pass a Python list directly to json.loads().

# Error Example
import json
my_list = ['Alice', 'Bob', 'Carl']
try:
# ⛔️ TypeError: the JSON object must be str, bytes or bytearray, not list
result = json.loads(my_list)
except TypeError as e:
print(e)

Solution: Similar to dictionaries, if you have a list, use json.dumps() to convert it to a JSON string if needed.

Converting Lists to JSON Strings (json.dumps())

# Correct Usage
import json
my_list = ['Alice', 'Bob', 'Carl']
my_json_str = json.dumps(my_list) # Convert list to JSON string
print(my_json_str) # Output: ["Alice", "Bob", "Carl"]
print(type(my_json_str)) # Output: <class 'str'>

Error: ... not TextIOWrapper (File Objects)

Cause & Solution

This happens when you pass a file object (like the one returned by open()) directly to json.loads().

# Error Example
import json
file_name = 'example.json' # Assume this file exists and contains {"name": "Alice", "age": 30}
try:
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)
except TypeError as e:
print(e)
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")

Solution: Use the json.load() function, which is designed to read from file objects.

Using json.load() for Files

# Correct Usage
import json
file_name = 'example.json' # Assume this file exists and contains {"name": "Alice", "age": 30}
try:
with open(file_name, 'r', encoding='utf-8') as f:
my_data = json.load(f) # Use json.load() for files
print(my_data) # Output: {'name': 'Alice', 'age': 30}
print(type(my_data)) # Output: <class 'dict'>
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
except json.JSONDecodeError:
print(f"Error: Could not decode JSON from '{file_name}'.")

Reading File Content Before json.loads()

Alternatively (though less common), read the file's content into a string first, then use json.loads():

# Alternative Usage
import json
file_name = 'example.json' # Assume this file exists
try:
with open(file_name, 'r', encoding='utf-8') as f:
file_content_string = f.read() # Read content into string
my_data = json.loads(file_content_string) # Use json.loads() on the string
print(my_data)
print(type(my_data))
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
except json.JSONDecodeError:
print(f"Error: Could not decode JSON from '{file_name}'.")

Error: ... not Response (requests Library)

Cause & Solution

This specific error occurs when working with the requests library and passing the entire Response object to json.loads().

# Error Example
import json
import requests
try:
res = requests.get('https://reqres.in/api/users')
res.raise_for_status() # Check for HTTP errors
# ⛔️ TypeError: the JSON object must be str, bytes or bytearray, not Response
parsed = json.loads(res)
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
except TypeError as e:
print(e)

Solution: The requests library provides a convenient .json() method on the Response object to directly parse the JSON content.

Using the .json() Method on Responses

# Correct Usage
import requests
try:
res = requests.get('https://reqres.in/api/users')
res.raise_for_status() # Good practice: check for request errors

parsed = res.json() # Call the .json() method

print(parsed)
print(type(parsed)) # Output: <class 'dict'> (or list, depending on API)
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
except json.JSONDecodeError:
print("Error: Response was not valid JSON.")

Choosing the Right JSON Method: load vs. loads, dump vs. dumps

  • json.loads(json_string): Load String - Parses a JSON string/bytes/bytearray into a Python object.
  • json.load(file_object): Load from file - Reads from a file-like object containing JSON and parses it into a Python object.
  • json.dumps(python_object): Dump String - Converts a Python object into a JSON formatted string.
  • json.dump(python_object, file_object): Dump to file - Writes a Python object as JSON to a file-like object.

Checking Variable Types

If you're unsure about the type of an object you're passing to a json function, use type() or isinstance():

my_var = {'a': 1}
print(type(my_var)) # Output: <class 'dict'>
print(isinstance(my_var, str)) # Output: False
print(isinstance(my_var, dict)) # Output: True

Conclusion

The TypeError: the JSON object must be str, bytes or bytearray arises from using json.loads() with an inappropriate object type.

By understanding that json.loads() expects JSON data (as a string, bytes, or bytearray) and using the correct functions (json.load() for files, json.dumps() for converting Python objects to JSON strings, or .json() for requests responses), you can effectively avoid this error and work seamlessly with JSON data in Python.