Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Gantas Vaičiulėnas
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(...)
.
Here is an example of how the error occurs.
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.
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.
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.
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.
Since the str
object doesn't implement a loads()
method, the error is
caused.