尝试使用 python 从 json 文件访问数据时发生错误"TypeError: list indices must be integers or slices, not str"



我试图访问json中的一个部分,但它给了我这个错误:TypeError: list indices must be integers or slices, not str。这是我的json:

{
"users": [
{
"coins": 50,
"id": 1234,
"items": [
{
"collectable1": 3,
"collectable2": 2,
"collectable3": 1
}
]
}
]
}

这是我的python:

with open("shoptestjson.json", "r+") as f:
json_obj = json.loads(f.read())
users = json_obj["users"]
for user in users:
if user["id"] == 1234:
collectable1 = user["items"]
print(str(collectable1["collectable1"]))
else:
pass

当我尝试只访问用户["items"]时,它是有效的,但当我尝试访问用户["items"]中的字段时,它不起作用。我在这里做错了什么?如果你帮忙,请提前感谢!

它不起作用,因为分配给局部变量collectable1user["items"]是一个列表。列表的项需要使用整数索引进行访问。

为了访问示例中的字段,您需要

print(user["items"][0]["collectable1"])

[0]用于访问密钥"items"所指的列表的第一个也是唯一一个项目

相关内容

最新更新