【发布时间】: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