AttributeError: 'dict' object has no attribute 'read'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

AttributeError: 'dict' object has no attribute 'read' #

The "AttributeError: 'dict' object has no attribute 'read'" occurs when we try to access the read attribute on a dictionary, e.g. by passing a dict to json.load(). To solve the error, use the json.dumps() method if trying to convert a dictionary to JSON.

attributeerror dict object has no attribute read

Here is an example of how the error occurs.

main.py
import json my_dict = {"name": "Alice", "age": 30} # ⛔️ AttributeError: 'dict' object has no attribute 'read' json_str = json.load(my_dict)

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

main.py
import json my_dict = {"name": "Alice", "age": 30} json_str = json.dumps(my_dict) print(json_str) # 👉️ '{"name": "Alice", "age": 30}'' print(type(json_str)) # 👉️ <class 'str'>

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

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

main.py
import json json_str = r'{"name": "Alice", "age": 30}' my_dict = json.loads(json_str) print(type(my_dict)) # 👉️ <class 'dict'>

If the data being parsed is not a valid JSON document, a JSONDecodeError is raised.

If you are trying to use the json.load() method to deserialize a file to a Python object, open the file and pass the file object to 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}

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. If you call the json.load() method with a dictionary, it tries to call the read() method on the dictionary.

A good way to start debugging is to print(dir(your_object)) and see what attributes a dictionary has.

Here is an example of what printing the attributes of a dict looks like.

main.py
my_dict = {'name': 'Alice', 'age': 30} # [...'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', # 'pop', 'popitem', 'setdefault', 'update', 'values' ...] print(dir(my_dict))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: 'dict' object has no attribute error".

Since dict objects don't have an read() method, the error is caused.

Use the search field on my Home Page to filter through my more than 3,000 articles.