Reputation: 233
So I am pulling some json data using an API and it initially looks like this:
{
"result": {
"elements": [
{
"id": "SV_3s0FmbrNancSmsB",
"name": "Test Survey",
"ownerId": "sdfsdfasdf",
"lastModified": "2016-08-09T21:33:27Z",
"isActive": false
},
{
"id": "SV_dgJOVyJvwZR0593",
"name": "Test Survey",
"ownerId": "sdfdsfsdfs",
"lastModified": "2016-08-04T17:53:37Z",
"isActive": true
}
],
"nextPage": null
},
"meta": {
"httpStatus": "200 - OK"
}
}
So I want to pull all of the ids within this JSON using Python, and here is my code:
url = "random.com"
headers = {
'x-api-token': "dsfsdagdfa"
}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
id_0 = data['result']['elements'][0]['id']
print(id_0)
This will basically just print the first Id within the created array. What would I do to get all of the ids?
Upvotes: 5
Views: 9324
Reputation: 30136
How about:
ids = [element['id'] for element in data['result']['elements']]
Upvotes: 2
Reputation: 974
You can use this oneliner:
ids = [element['id'] for element in data['result']['elements']]
Upvotes: 10
Reputation: 2877
This should work. Im sure there is a more elegant way with map or list comprehension.
ids = []
for elem in data['result']['elements']:
ids.append(elem['id'])
If you want to evaluate this lazily, make a generator comprehension!
ids = (element['id'] for element in data['result']['elements'])
Upvotes: 4