I am trying to find the owner login, owner key, license key, license name for all the repositories which were created_at or after ‘2013-06-04’ from the https://api.github.com/users/mralexgray/repos.
This is using nested list but unable to find out the result: My code is given below:
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'])
I am getting an error:
Traceback (most recent call last):File "<string>", line 11, in <module>
TypeError: list indices must be integers or slices, not str
Not sure how to resolve this issue to findout the key values and parameters. Need help for this.
CodePudding user response:
The structure of the response j
is:
[
{
"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"
}
]
- Accessing
j['owner']
is incorrect becausej
is a list. What you want is the dictionary inside an item in the list such asj[0]['owner']
. - Accessing
j[0]['owner']['license']
is also incorrect because"license"
is not a key of the"owner"
dictionary. Instead, it is a key of the outer dictionaryj[0]['license']
. - Accessing
each['login']['id']
is also incorrect because the field"login"
is a string, not a dictionary. Instead it is another key in the same dictionaryj[0]['owner']['login']
alongsidej[0]['owner']['id']
.
With the structure I pasted above as reference, you can try this instead:
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"])
If you wish to filter the results by the created_at
field:
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"])
CodePudding user response:
j
is an array, so you cannot access owner
in it. I guess you'd want more something like:
for each in j:
...
Edit: You could even extract all the ids in a quite straightforward way:
ids = [x['owner']['id'] for x in j]
CodePudding user response:
In your code j
is list
you need iterate over it like below:
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']))