Python :: iterating through nested JSON results

iterating through JSON resultsmay get confused from time to time. let's say I have functionthis:

def get_playlist_owner_ids(query):

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

I can get id_it working.

but how to iterate through a loop for i in xso that I am returnALL ids_?

+4
source share
4 answers
results['playlists']['items'][0]['owner']['id']
                              ^___ this is a list index

In this way:

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

It is often convenient to create intermediate variables to make things more readable.

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

, , , . , , .

+3

?

def get_playlist_owner_ids(query):
    results = sp.search(q=query, type='playlist')
    for item in results['playlists']['items']:
        yield item['owner']['id']
0

You can iterate over results['playlists']['items']or, even better, use list comprehension:

def get_playlist_owner_ids(query):

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

In practice, your document looks something like this:

{ "playlists": {
    "items":[
        {"owner":{"id":"1"},...},                 
        {"owner":{"id":"2"},...},
        {"owner":{"id":"3"},...},
        ...,
}

So you need to iterate over the list of items.

You can do something like this

ids = []
items = results['playlists']['items']
for item in items:
    ids.append(item['owner']['id'])

return ids

Or if you want a single line:

ids = [item['owner']['id'] for owner in results['playlists']['items']]
0
source

Source: https://habr.com/ru/post/1651846/


All Articles