data_garden data_garden - 3 months ago 13
JSON Question

python :: iterate through nested JSON results

iterating through

JSON
results
can get quite confusing at times.
say I have a
function
like so:

def get_playlist_owner_ids(query):

results = sp.search(q=query, type='playlist')
id_ = results['playlists']['items'][0]['owner']['id']
return (id_)


I can fetch the
id_
, it works.

but how do I iterate using a
for i in x
loop so I
return
ALL
ids_
?

Answer
results['playlists']['items'][0]['owner']['id']
                              ^___ this is a list index

Thus:

for item in results['playlists']['items']:
    print(item['owner']['id'])

It is often convenient to make intermediate variables in order to keep things more readable.

playlist_items = results['playlists']['items']
for item in playlist_items:
    owner = item['owner']
    print(owner['id'])

This is assuming I have correctly guessed the structure of your object based on only what you have shown. Hopefully, though, these examples give you some better ways of thinking about splitting up complex structures into meaningful chunks.