【问题标题】:TypeError: list indices must be integers or slices, not str - JSON, Python errorTypeError:列表索引必须是整数或切片,而不是 str - JSON,Python 错误
【发布时间】:2017-12-03 11:21:03
【问题描述】:
    {
        "gameId": 32,
        "participantIdentities": [
            {
                "player": {
                    "id": "123",
                    "name": "xxx",
                },
                "participantId": 1
            },
            {
                "player": {
                    "id": "123",
                    "name": "yyyy",   
                },
                "participantId": 2
            }
        ]

        "gameDuration": 143,
    }

我正在尝试在 python 3 中的这个 json 文件中打印名称

    list_id = []
    for info in matchinfo['participantIdentities']['player']['name']:
        list_id.append(info)

但我在下面收到以下错误

    TypeError: list indices must be integers or slices, not str

如何获取'name'的内容?

【问题讨论】:

    标签: json python-3.x api


    【解决方案1】:

    有几个问题:

    1. 您提供的 JSON 无效。 matchinfo['participantIdentities'] 应该是一个列表,但您提供的 JSON 缺少结束 ]

    2. matchinfo['participantIdentities'] 是一个列表,因此您应该提供一个索引(例如matchinfo['participantIdentities'][0]['player']['summonerId'])或遍历所有matchinfo['participantIdentities'] 条目。

    3. 您正在尝试访问一个甚至不存在的密钥(至少在您提供的 JSON 中)。任何地方都没有'summonerId' 键。

    【讨论】:

    • 1.它仍然无效(尝试调用json.loads)。 2. 您尝试访问的密钥仍然不存在。 3.我回答中的第2点仍然回答了您的问题。
    猜你喜欢
    • 2017-11-19
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2020-11-21
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多