我正在尝试从https://api.github.com/users/mralexgray/repos中查找所有存储库的所有者登录、所有者密钥、许可证密钥、许可证名称,这些存储库是created_at或之后的2013-06-04。
这是使用嵌套列表,但无法找到结果:我的代码如下所示:
import requests
import json
url = 'https://api.github.com/users/mralexgray/repos'
content = requests.get(url).content
j = json.loads(content)
#print(j)
for each in j['owner']['license']:
print (each ['login']['id'])我收到一个错误:
Traceback (most recent call last):File "<string>", line 11, in <module>
TypeError: list indices must be integers or slices, not str不确定如何解决此问题以找出关键值和参数。我需要你的帮助。
发布于 2021-09-14 10:09:29
响应j的结构如下:
[
{
"owner": {
"login": "something",
"id": 12345
}
"license": None,
"created_at": "2012-10-06T16:37:39Z"
},
{
"owner": {
"login": "another",
"id": 6789
}
"license": None,
"created_at": "2014-02-12T11:12:13Z"
}
]访问j['owner']的
j是一个列表。您想要的是列表中条目内的字典也是不正确的,因为"license"不是"owner"字典的关键字。相反,它是外部字典的关键字,因为字段"login"是字符串,而不是字典,所以each['login']['id']也是不正确的。相反,它是与j[0]['owner']['id'].并列的同一字典j[0]['owner']['login']中的另一个关键字
使用我在上面粘贴的结构作为参考,你可以尝试这样做:
import json
import requests
url = 'https://api.github.com/users/mralexgray/repos'
content = requests.get(url).content
j = json.loads(content)
for each in j:
print(each["owner"]['login'], each['owner']['id'], each['license'], each["created_at"])如果要按created_at字段过滤结果:
for each in filter(lambda data: data["created_at"] >= "2013-06-04", j):
print(each["owner"]['login'], each['owner']['id'], each['license'], each["created_at"])发布于 2021-09-14 10:02:19
j是一个数组,所以您不能在其中访问owner。我猜你会想要更多的东西,比如:
for each in j:
...编辑:您甚至可以以一种非常简单的方式提取所有ids:
ids = [x['owner']['id'] for x in j]发布于 2021-09-14 10:09:04
在你的代码中,j是list,你需要像下面这样迭代它:
import requests
import json
url = 'https://api.github.com/users/mralexgray/repos'
content = requests.get(url).content
j = json.loads(content)
for i in j:
print((i['owner']['id']))https://stackoverflow.com/questions/69175682
复制相似问题