【发布时间】: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