Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python :: iterate through nested JSON results

iterating through JSON results can get quite confusing at times. say I have a functionlike 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_?

like image 784
8-Bit Borges Avatar asked Aug 19 '16 23:08

8-Bit Borges


1 Answers

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.

like image 174
Two-Bit Alchemist Avatar answered Sep 25 '22 10:09

Two-Bit Alchemist