【问题标题】:How to extract data that's in JSON with Python如何使用 Python 提取 JSON 格式的数据
【发布时间】: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 解决了它,但现在我遇到了另一个问题。
  • 您能否提供更多信息,说明问题究竟是在哪里引起的?也许还有堆栈跟踪?

标签: python json discord


【解决方案1】:

你应该改变:

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

作者:

for entry in a:

【讨论】:

    【解决方案2】:

    这应该可以解决您的错误。您不需要新的 b 对象。 'entry' 变量将包含列表中的元素,在这种情况下,它将是列表中的字典对象。因此,您可以使用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']
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 2022-01-13
      • 2021-04-24
      • 1970-01-01
      • 2022-11-21
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多