【问题标题】:TypeError: string indices must be integers when filtering values in a JSON in PythonTypeError:在 Python 中过滤 JSON 中的值时,字符串索引必须是整数
【发布时间】:2020-05-18 03:45:23
【问题描述】:
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: string indices must be integers。我究竟做错了什么?谢谢

【问题讨论】:

  • 当字典更容易浏览时,为什么要将字典转换为 json?
  • 嗯,这是对显然要处理 json 的最终 API 的测试,我需要学习如何导航和处理 json。

标签: python json dictionary flask


【解决方案1】:

错误原因:您正在迭代字典的键。所以最初 ipeople 这是一个字符串。您正在尝试i["owner"],它会引发错误,因为i 是一个字符串。

x其实是一个字典,不用json包就可以直接访问。

代码:

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

如果你需要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 = z["people"]
for i in people:
    if i["owner"] == "bob":
        print(i['petname'])
        break

输出:

fido

【讨论】:

    【解决方案2】:

    您正在迭代基础 dictionary 而不是在 people 下迭代 list

    迭代包含listz["people"],而不是迭代z
    解决方案

    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
    

    另外,我认为不需要使用

    y = json.dumps(x)
    z = json.loads(y)
    

    您可以简单地使用基本字典x

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

    【讨论】:

    • 如果用户以字符串形式接收 API 数据,则需要 json
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    相关资源
    最近更新 更多