Python检查带有变量的json文件

2024-04-25 17:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

Tags: 文件字符串httpsimagegtjsondatacomment
2条回答
contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
                       ^                      ^

这表示未知长度的列表的位置。GraphImagesdata键保存列表。要在列表上迭代,可以使用如下for .. in语句:

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

请注意,您正在直接使用itemitem在循环的每个相应迭代上依次变为{}、{}和{}。您不需要使用任何数字索引,也不需要计算任何xy

根据您的情况,您需要两个这样的循环:

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

  try:

    comment = contact["GraphImages"][x]["comments"]["data"][y]["text"] #Check if post x has comments
    for comments_total in contact["GraphImages"][x]["comments"]["data"]:
      comment = contact["GraphImages"][x]["comments"]["data"][y]["text"]
      comment_author = contact["GraphImages"][x]["comments"]["data"][y]["owner"]["username"]
      print(comment_author," : ",comment)
      y = y + 1

  except IndexError:

    print("Not commnet in", x, 'Post')


  x = x + 1

相关问题 更多 >

    热门问题