如何提取';JSON与Python的结合
我不完全确定如何使用这个json输出在python中列出它们,我的意思是循环遍历它们并从json输出中收集信息 JSON输出位于: (从OMBIAPI收集的数据,该API使用Traktr作为提供程序。) 代码段:如何提取';JSON与Python的结合,python,json,discord,Python,Json,Discord,我不完全确定如何使用这个json输出在python中列出它们,我的意思是循环遍历它们并从json输出中收集信息 JSON输出位于: (从OMBIAPI收集的数据,该API使用Traktr作为提供程序。) 代码段: request_headers = {'apiKey': pmrs_api_token, 'content-type': 'application/json'} async with aiohttp.ClientSession() as ses:
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'])
与aiohttp.ClientSession()作为ses异步:
与ses.get(pmrs\u full\u端点,headers=request\u headers)异步作为响应:
a=wait response.json()
如欲进入
b=wait response.json()
打印(类型(b))#输出
标题=(b[条目]['title'])
first_aired=(b[条目]['firstAired'])
desc=(b[条目][概述])
再次显示有关类型的错误…:/ 您应该更改:
for entry in (a['response']):
作者:
这将修复您的错误。您不需要新的b对象。“entry”变量将包含列表中的元素,在这种情况下,它将是列表中的dictionary对象。因此,您可以使用
条目['title']
提取值
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:
title = entry['title']
first_aired = entry['firstAired']
desc = entry['overview']
JSON解码为Python的dict列表。我假设
a
是一个列表,所以只需迭代该列表即可。您可以通过打印a
,或打印键入(a)
@PM2Ring进行检查,但现在我遇到了另一个问题。您能否提供更多信息,说明问题的确切原因?也许还有stacktrace?
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:
title = entry['title']
first_aired = entry['firstAired']
desc = entry['overview']