简体   繁体   English

python ::迭代嵌套的JSON结果

[英]python :: iterate through nested JSON results

iterating through JSON results can get quite confusing at times. 迭代JSON results有时会让人感到困惑。 say I have a function like so: 说我有这样的function

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. 我可以获取id_ ,它可以工作。

but how do I iterate using a for i in x loop so I return ALL ids_ ? 但是我如何for i in x循环中使用for i in x进行迭代for i in x所以我return所有ids_

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. 但是,希望这些示例能够为您提供一些更好的方法来考虑将复杂结构拆分为有意义的块。

How about this? 这个怎么样? You can use generator to achieve your goal 您可以使用发电机来实现目标

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

You could iterate over results['playlists']['items'] , or, better yet, use list comprehension: 你可以迭代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']]

In practice your document is something like this: 在实践中,您的文档是这样的:

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

So you have to loop 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 to a one line: 或者如果你想要一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM