Python检查带有变量的json文件
我有一个json文件,它有18个子字符串,如下所示: 但是我有更多的json文件,它们有不同数量的子字符串。所以我这样做是为了找出文本中有多少:Python检查带有变量的json文件,python,json,loops,for-loop,variables,Python,Json,Loops,For Loop,Variables,我有一个json文件,它有18个子字符串,如下所示: 但是我有更多的json文件,它们有不同数量的子字符串。所以我这样做是为了找出文本中有多少: import json json_str = open('jsonfile.txt', 'r').read() contact = json.loads(json_str) 所以图的总数是18 . 每个子字符串都有注释->数据->0->所有者->用户名 所以我想打印用户名 comment_author = contact["GraphImage
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
这表示未知长度的列表的位置。图形和数据键保存列表。要遍历列表,请使用for。。声明如下:
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
请注意,您正在直接使用项。在循环的每个迭代中,项目将依次变为“foo”、“bar”和“baz”。您不需要使用任何数字索引,也不需要计算任何x或y
根据您的情况,您需要两个这样的循环:
for graph_image in contact['GraphImages']:
for comment in graph_image['comments']['data']:
print(comment['text'], comment['owner']['username'])
对于联系人中的图形图像['GraphImages']:打印图形图像…!这不是我想要的。我想这样做:comment_author=contact[GraphImages][0][comments][data][0][owner][username]///comment_author=contact[GraphImages][1][comments][data][0][owner][data][1][comments][data][owner][username]///comment_author=contact[GraphImages 2][comments][data][data][0][owner][username][username][,我暗示了你需要去哪里。您希望在列表上进行迭代。使用一个简单的。。在里面为此。不需要射程。从这里开始。哦,是的,这很好,让事情变得更简单。所以我这样做了:x=0///对于联系人['GraphImages']中的graph_图像:///printcontact[GraphImages][x][comments][data][0][owner][username]///x=x+1///但我仍然得到索引器:列表索引超出范围:
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
for graph_image in contact['GraphImages']:
for comment in graph_image['comments']['data']:
print(comment['text'], comment['owner']['username'])