使用 Python 迭代节点内的对象数组

Iterate array of objects inside node using Python

我使用此功能读取 Instagram JSON 文件的内容并将信息保存在字典中。我有以下问题:如何迭代 ['node']['edge_media_to_tagged_user']['edges'] 中的对象数组?这是我的代码:

info = {}

def store_data(file):

    with open(file) as f:
        data = json.load(f)

        try:
            info["tagged_users"] = data['node']['edge_media_to_tagged_user']['edges'][0]['node']['user']['username']
        except KeyError:
            info["tagged_users"] = "null"
        return info

如下图所示,数组中有 12 个对象,我的代码仅适用于第一个 [0]。我需要得到每个人的用户名。

Array example

基本上:

data['node']['edge_media_to_tagged_user']['edges'][0]['node']['user']['username']
data['node']['edge_media_to_tagged_user']['edges'][1]['node']['user']['username']
data['node']['edge_media_to_tagged_user']['edges'][2]['node']['user']['username']
data['node']['edge_media_to_tagged_user']['edges'][3]['node']['user']['username']
...
data['node']['edge_media_to_tagged_user']['edges'][x]['node']['user']['username']

当然,您的代码仅适用于一条边 - 那就是您要求的

data['node']['edge_media_to_tagged_user']['edges'] 下是字典列表。

要遍历列表,您只需使用 for 循环

for each_edge in data['node']['edge_media_to_tagged_user']['edges']:
    print(each_edge) # or whatever you wish to do here