python ::迭代嵌套的JSON结果

时间:2016-08-19 23:32:32

标签: python json loops iteration

迭代JSON results有时会让人感到困惑。 说我有function这样:

def get_playlist_owner_ids(query):

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

我可以抓取id_,但是有效。

但如何使用for i in x循环进行迭代,以便我return全部ids_

4 个答案:

答案 0 :(得分:3)

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

因此:

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

制作中间变量以使事物更具可读性通常很方便。

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

这是假设我已经根据您所显示的内容正确猜出了对象的结构。但是,希望这些例子可以让您更好地考虑将复杂结构拆分为有意义的块。

答案 1 :(得分:0)

这个怎么样?您可以使用生成器来实现目标

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

答案 2 :(得分:0)

你可以迭代results['playlists']['items'],或者更好的是,使用列表理解:

def get_playlist_owner_ids(query):

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

答案 3 :(得分:0)

在实践中,您的文档是这样的:

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

所以你必须循环遍历项目列表。

你可以做这样的事情

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

return ids

或者如果你想要一行:

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