j doe j doe - 2 years ago 85
JSON Question

How to get all of the "ids" within a python array

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']


This will basically just print the first Id within the created array. What would I do to get all of the ids?

Answer Source

You can use this oneliner:

ids = [element['id'] for element in data['result']['elements']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download