AttributeError: ‘str’ 对象没有属性 ‘items’

AttributeError: ‘str’ 对象没有属性 ‘items’

AttributeError: ‘str’ object has no attribute ‘items’

当我们尝试items()在字符串而不是字典上调用方法时,会出现 Python“AttributeError: ‘str’ object has no attribute ‘items’”。items()要解决该错误,如果您有 JSON 字符串或更正分配并调用字典,请确保解析该字符串。

attributeerror str 对象没有属性项

下面是错误如何发生的示例。

主程序
# 👇️ this is a string my_dict = '{"name": "Alice", "age": 30}' # ⛔️ AttributeError: 'str' object has no attribute 'items' print(my_dict.items())

我们试图items()在字符串上调用该方法并得到错误。

如果您有 JSON 字符串,请使用该json.loads()方法将其解析为本机 Python 字典。

主程序
import json my_dict = '{"name": "Alice", "age": 30}' # 👇️ parse JSON string to native Python dict parsed = json.loads(my_dict) # 👇️ dict_items([('name', 'Alice'), ('age', 30)]) print(parsed.items())

在调用该方法之前,我们使用该json.loads()方法将 JSON 字符串解析为 Python 字典items()

如果您需要在调用该方法之前检查该值是否为字典items()
,请使用该
isinstance函数。

主程序
my_dict = {"name": "Alice", "age": 30} if isinstance(my_dict, dict): # 👇️ dict_items([('name', 'Alice'), ('age', 30)]) print(my_dict.items())

如果传入的对象是传入类的实例或子类,则isinstance
函数返回。
True

如果您发出 HTTP 请求,请确保您没有将headers
字典转换为 JSON。

主程序
import requests def make_request(): res = requests.post( 'https://reqres.in/api/users', data={'name': 'John Smith', 'job': 'manager'}, # 👇️ should be a Python dictionary (NOT json str) headers={'Accept': 'application/json', 'Content-Type': 'application/json'} ) print(res.json()) # parse JSON response to native Python object make_request()

headers关键字参数应该是 Python 字典,而不是 JSON 字符串

确保您没有json.dumps()在字典上调用该方法,因为那样会将其转换为 JSON 字符串。

主程序
import json my_dict = {"name": "Alice", "age": 30} print(type(my_dict)) # 👉️ <class 'dict'> # 👇️ json.dumps() converts a Python object to JSON string json_str = json.dumps(my_dict) print(type(json_str)) # 👉️ <class 'str'>

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

If you have a JSON string and are trying to parse it into a native Python
dictionary, use the json.loads() method.

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

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

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

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 class’s attributes, and recursively of the
attributes of its bases.

如果您尝试访问不在此列表中的任何属性,您将收到“AttributeError:str object has no attribute error”。

由于items()不是字符串实现的方法,所以报错。

结论

当我们尝试items()在字符串而不是字典上调用方法时,会出现 Python“AttributeError: ‘str’ object has no attribute ‘items’”。items()要解决该错误,如果您有 JSON 字符串或更正分配并调用字典,请确保解析该字符串。