AttributeError: 'str' object has no attribute 'loads'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

AttributeError: 'str' object has no attribute 'loads' #

The "AttributeError: 'str' object has no attribute 'loads'" occurs when we call the loads() method on a string. To solve the error, make sure you aren't overriding the json module and call the loads method on the module, e.g. json.loads(...).

attributeerror str object has no attribute loads

Here is an example of how the error occurs.

main.py
import json # 👇️ overriding json module setting it to a string json = '{"name": "Alice", "age": 30}' # ⛔️ AttributeError: 'str' object has no attribute 'loads' result = json.loads(json)

The issue in the code snippet is that we reassigned the json module to a string and tried to call the loads() method on the string.

To solve the error, make sure you aren't reassigning the json module in your code and call the loads() method on the module.

main.py
import json my_json = '{"name": "Alice", "age": 30}' result = json.loads(my_json) print(result) # 👉️ {'name': 'Alice', 'age': 30}

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

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

Alternatively, you can import the loads method from the json module if the json variable is shadowed in your code.

main.py
from json import loads my_json = '{"name": "Alice", "age": 30}' result = loads(my_json) print(result) # 👉️ {'name': 'Alice', 'age': 30}

The example only imports the loads() method from the json module, so it would work even if you are redefining json in your code.

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

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

main.py
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

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: str object has no attribute error".

Since the str object doesn't implement a loads() method, the error is caused.

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