如何用Python提取JSON格式的数据

2024-09-28 03:13:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我不完全确定如何使用这个json输出在python中列出它们,我的意思是循环使用它们并从json输出中收集信息?你知道吗

JSON输出位置:https://hastebin.com/riroteqiso.json (从ombiapi收集的数据,该API使用Traktr作为提供者。)

代码段:

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'])

再次给我一个关于类型的错误。。。:/


Tags: injsonforasyncaiohttpresponserequestas
2条回答

您应该更改:

for entry in (a['response']):

签署人:

for entry in a:

这将修复您的错误。您不需要新的b对象。“entry”变量将包含列表中的元素,在本例中,它将是列表中的dictionary对象。因此,您可以使用entry['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']

相关问题 更多 >

    热门问题