【问题标题】:Twitch API json dictionary error list indices must be integers not strTwitch API json 字典错误列表索引必须是整数而不是 str
【发布时间】:2020-06-20 13:41:45
【问题描述】:
try:
    response = requests.get('https://api.twitch.tv/kraken/streams/followed', headers=headers)
    data = response.json()
except (KeyError, ValueError):
    print("Error - make sure your OAuth is formatted correctly in oauth.txt")
    sys.exit(1)
channelName = data["streams"]["channel"]["name"]
channelGame = data["streams"]["channel"]["game"]
channelViewers = str(data["streams"]["viewers"])
streamType = data["streams"]["stream_type"]
print(channelName, channelGame, channelViewers, streamType)

我得到的错误是列表索引必须是整数或切片,而不是 str

从 twitch 我得到一个 json 字典:

{'streams': [{'_id': 2011610081, 'game': 'Sports & Fitness', 'broadcast_platform': 'live', 'community_id': '', 'community_ids': [], 'viewers': 12399, 'video_height': 900, 'average_fps':59, 'delay': 0, 'created_at': '2020-06-20T12:06:14Z', 'is_playlist': False, 'stream_type': 'live' }字典要长很多

如何在不出错的情况下访问它

【问题讨论】:

  • streams 是一个列表,您需要循环访问或使用data["streams"][0] 之类的索引来访问这些值。

标签: python json python-3.x dictionary


【解决方案1】:

这是一个你已经迭代过的列表 类似这样的东西

使用 for 循环遍历它

for i in data['streams']:
    print(i['_id'] ,i['game'])

或选择索引

data["streams"][0]['_id']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多