首页 > 解决方案 > Python检查带有变量的json文件

问题描述

我有一个 json 文件,它有 18 个子字符串,如下所示: https://i.stack.imgur.com/aVWuw.png https://i.imgur.com/0ABdcde.png

但是我有更多的 json 文件,这些文件具有不同数量的这些子字符串。所以我这样做是为了找出文本中有多少:

import json

json_str = open('jsonfile.txt', 'r').read()

contact = json.loads(json_str)

所以 GraphImages_total 是 18 。每个子字符串都有注释 --> 数据 --> 0 --> 所有者 --> 用户名 所以我想打印用户名。

comment_author = contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
print(comment_author)

这是针对 GraphImages_total = 0 但我想为所有人做这件事。

所以我需要一种方法来使它像这样:

for graph_image in contact['GraphImages']:
    comment_author = contact["GraphImages"][graph_image]["comments"]["data"][0]["owner"]["username"]
    print(comment_author)

但我得到这个错误:

comment_author = contact["GraphImages"][graph_image]["comments"]["data"][0]["owner"]["username"]IndexError: list index out of range

标签: pythonjsonloopsfor-loopvariables

解决方案


contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
                       ^                      ^

这表明未知长度的列表在哪里。和GraphImagesdata保存列表。要遍历列表,请使用for .. in如下语句:

my_list = ['foo', 'bar', 'baz']
for item in my_list:
    print(item)

请注意,您正在item直接使用。item将依次变为'foo','bar''baz'在循环的每个相应迭代中。您不需要使用任何数字索引,也不需要计算任何xor y

应用于您的情况,您需要两个这样的循环:

for graph_image in contact['GraphImages']:
    for comment in graph_image['comments']['data']:
        print(comment['text'], comment['owner']['username'])

推荐阅读