我有一个json文件,它有18个子字符串,如下所示: https://i.stack.imgur.com/aVWuw.pnghttps://i.imgur.com/0ABdcde.png
但是我有更多的json文件,它们有不同数量的子字符串。所以我这样做是为了找出文本中有多少:
import json
json_str = open('jsonfile.txt', 'r').read()
contact = json.loads(json_str)
所以图的总数是18 . 每个子字符串都有注释-->;数据-->;0-->;所有者-->;用户名 所以我想打印用户名
comment_author = contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
print(comment_author)
这是用于图形的\u总计=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
这表示未知长度的列表的位置。
GraphImages
和data
键保存列表。要在列表上迭代,可以使用如下for .. in
语句:请注意,您正在直接使用}、{}和{}。您不需要使用任何数字索引,也不需要计算任何
item
item
在循环的每个相应迭代上依次变为{x
或y
根据您的情况,您需要两个这样的循环:
相关问题 更多 >
编程相关推荐