Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeError:字符串索引必须是整数-JSON Python_Python_Json_Python 3.x_Python Requests - Fatal编程技术网

TypeError:字符串索引必须是整数-JSON Python

TypeError:字符串索引必须是整数-JSON Python,python,json,python-3.x,python-requests,Python,Json,Python 3.x,Python Requests,所以我得到了一个错误: 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 JSON如下所示: [ { "id": "

所以我得到了一个错误:

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
JSON如下所示:

[
  {
    "id": "771634716042461195", 
  },
  {
    "id": "771654126345781278", 
  }, 
  {
    "id": "771658044526034967", 
  }
]
我想打印出频道id,在本例中为: 771634716042461195和771654126345781278


非常感谢您的帮助。

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

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

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

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。希望这能帮助其他人。

转储
将对象转换为字符串。您是否打算使用
json.loads
将json字符串转换为列表/目录…?!或者,什么也没有,因为你已经用
.JSON()
为i in r:print(i['id'])
解码了JSON。我试图从字典中获取频道的id,而不是整个字典-尽管你的建议有效,但不是我想要的。我想这意味着获取“id['id']或id['id']时失败了为空/无,请再次检查您的令牌并确保请求获得状态代码
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