TypeError:在Python中过滤JSON中的值时,字符串索引必须为整数

x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
    y = json.dumps(x)
    z = json.loads(y)
    for i in z:
        if i["owner"] == "bob":
            print(i['petname'])
            break

该代码的目标是通过为所有者命名为“ bob”来返回“ fido”

但是我得到的只是TypeError:字符串索引必须是整数。我究竟做错了什么?谢谢

评论
  • 被窝﹖爱
    被窝﹖爱 回复

    You are iterating the base dictionary instead of iteration list under people

    Iterate over z["people"] which contains a list, instead of iterating z
    Solution

    x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
        y = json.dumps(x)
        z = json.loads(y)
        for i in z["people"]:
            if i["owner"] == "bob":
                print(i['petname'])
                break
    

  • miure
    miure 回复

    码:

    x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
    people = x["people"]
    for i in people:
        if i["owner"] == "bob":
            print(i['petname'])
            break
    

    If you need JSON:

    import json
    x = { "people": [{ "owner": "bob", "petname": "fido", "species": "dog", "size": "chunky"}, {"owner": "mary","petname": "marvin","species": "cat","size": "cat"}]}
    y = json.dumps(x)
    z = json.loads(y)
    people = x["people"]
    for i in people:
        if i["owner"] == "bob":
            print(i['petname'])
            break
    

    输出:

    fido
    

  • snihil
    snihil 回复

    当你做

    for i in z:
    

    每个密钥都被获取,即,i ='people'。所以当你这样做

    i["owner"]
    

    产生错误,因为我是一个字符串。 因此使用:

    for i in z:
        if z[i]["owner"] == "bob":
            print(z[i]['petname'])
            break