【问题标题】:TypeError: string indices must be integers - JSON PythonTypeError:字符串索引必须是整数 - JSON Python
【发布时间】:2020-10-30 09:09:36
【问题描述】:

所以我得到了错误:

Traceback (most recent call last):
 File "C:/Users/User/PycharmProjects/db/dm testing.py", line 12, in <module>
   for id in ids['id']:
TypeError: string indices must be integers

使用以下代码:

import requests
import json

token = 'mytoken'

headers = {
    'Authorization': token,
}

r = requests.get('https://canary.discordapp.com/api/v6/users/@me/channels', headers=headers).json()
ids=json.dumps(r)
for id in ids['id']:
    print(id)

JSON 看起来像这样:

[
  {
    "id": "771634716042461195", 
  },
  {
    "id": "771654126345781278", 
  }, 
  {
    "id": "771658044526034967", 
  }
]

我想打印出频道 ID,在本例中为: 771634716042461195 和 771654126345781278。

非常感谢任何帮助。

【问题讨论】:

  • dumps 将对象转换为字符串。您的意思是使用json.loads 将JSON 字符串转换为列表/字典……?!或者,什么都没有,因为您已经使用 .json() 解码了 JSON?
  • for i in r: print(i['id'])...?

标签: python json python-3.x python-requests


【解决方案1】:

好的,所以我找到了解决方案,这是我的最终代码:

import requests
import json

token = 'mytoken'

headers = {
    'Authorization': token,
}

r = requests.get('https://canary.discordapp.com/api/v6/users/@me/channels', headers=headers).json()
x = 0

for i in range(len(r)):
    print(r[x]['id'])
    x+=1

它会打印所有频道的 ID。希望这可以帮助其他人。

【讨论】:

    【解决方案2】:

    您正在将已解析的 json 转换回字符串,但您希望它是字典,而不是字符串。您可以完全删除第二行。

    r = requests.get('https://canary.discordapp.com/api/v6/users/@me/channels', headers=headers).json()
    for id in r['id']:
        print(id)
    

    【讨论】:

    • 我正在尝试从字典中获取频道的 ID,而不是从整个字典中获取 - 尽管您的建议确实有效,但这不是我所追求的。
    • 我认为这意味着获取 "ids['id']" 或 ids['id'] 为空/无,请再次检查您的令牌并确保请求获取 status_code
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2016-03-26
    • 2016-02-17
    • 2023-03-03
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多