【发布时间】:2018-11-02 08:34:45
【问题描述】:
我不完全确定如何使用这个 json 输出在 python 中列出它们,我的意思是循环它们并从 JSON 输出中收集信息?
JSON 输出在:https://hastebin.com/riroteqiso.json (从使用 Traktr 作为提供者的 Ombi API 收集的数据。)
代码sn-p:
request_headers = {'apiKey': pmrs_api_token, 'content-type': 'application/json'}
async with aiohttp.ClientSession() as ses:
async with ses.get(pmrs_full_endpoint, headers=request_headers) as response:
a = await response.json()
for entry in (a['response']):
print(entry)
错误回溯:
Traceback (most recent call last):
File "/home/sm/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **kwargs)
File "/home/sm/Programming/Python/Discord-Bots/Plex-bot/cogs/ombi.py", line 85, in populartv
for entry in (a['response']):
TypeError: list indices must be integers or slices, not str
编辑:
按照建议更改它已解决,但现在我遇到了另一个问题。
async with aiohttp.ClientSession() as ses:
async with ses.get(pmrs_full_endpoint, headers=request_headers) as response:
a = await response.json()
for entry in a:
b = await response.json()
print(type(b)) # Outputs <class 'list'>
title = (b[entry]['title'])
first_aired = (b[entry]['firstAired'])
desc = (b[entry]['overview'])
再次给我一个关于类型的错误...:/
【问题讨论】:
-
该 JSON 解码为 Python 字典列表。我假设
a是一个列表,所以只需遍历该列表。可以打印a,或者打印type(a) -
@PM2Ring 解决了它,但现在我遇到了另一个问题。
-
您能否提供更多信息,说明问题究竟是在哪里引起的?也许还有堆栈跟踪?