简体   繁体   中英

Error "TypeError: list indices must be integers or slices, not str" occurs when trying to access data from a json file, with python

I am trying to access a part in my json, but it gives me this error: TypeError: list indices must be integers or slices, not str . Here is my json:

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

and here is my 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

It works when I try to just access user["items"], but it doesnt work when I try to access a field in user["items"]. What am I doing wrong here? Thanks in advance if you help!

It doesn't work because user["items"] , which you assigned to the local variable collectable1 , is a list. A list's items need to be accesses with integer indices.

In order to access a field in your example, you would need

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

The [0] is used to access the first and only item of the list that the key "items" refers to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM