我試圖從https://api.github.com/users/mralexgray/repos中找到所有在'2013-06-04'或之后創建的存盤庫的所有者登錄、所有者密鑰、許可證密鑰和許可證名稱。
這是在使用嵌套串列,但無法找出結果。我的代碼如下:
import requests
import json
url = 'https://api.github.com/users/mralexgray/repos'/span>
content = requests.get(url).content
j = json.load(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索引必須是整數或片,不是str。
不知道如何解決這個問題,找出關鍵值和引數。這需要幫助。
uj5u.com熱心網友回復:
回應j的結構是:
[
{
"所有者": {
"login": "something",
"id": 12345。
}
"license": None,
"created_at": "2012-10-06T16:37:39Z"
},
{
"所有者": {
"login": "另一個"。
"id": 6789。
}
"license": None,
"created_at": "2014-02-12T11:12:13Z"
}
]
- 訪問
j['owner']是不正確的,因為j是一個串列。你想要的是串列中的一個專案里面的字典,例如j[0]['owner']. - 訪問
j[0]['owner']['license']也是不正確的,因為"license"不是"owner"字典中的一個鍵。相反,它是外層字典j[0]['license']的一個鍵。 - 訪問
each['login']['id']也是不正確的,因為欄位"login"是一個字串,不是一個字典。相反,它是同一個字典中的另一個鍵j[0]['owner']['login']與j[0]['owner']['id']并列。
以我上面粘貼的結構為參考,你可以試試這樣做:
import json
import requests
url = 'https://api.github.com/users/mralexgray/repos'/span>
content = requests.get(url).content
j = json.load(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"]
uj5u.com熱心網友回復:
j是一個陣列,所以你不能在其中訪問owner。我想你會想要更多類似的東西:
for each in j。
...
編輯。 你甚至可以用一種很直接的方式來提取所有的ID:
ids = [x['owner']['id'] for X in j]
uj5u.com熱心網友回復:
在你的代碼中,j是list,你需要像下面這樣對它進行迭代:
import requests
import json
url = 'https://api.github.com/users/mralexgray/repos'/span>
content = requests.get(url).content
j = json.load(content)
for i in j:
print((i['owner']['id'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/308564.html
標籤:
