Python检查带有变量的json文件 [英] Python check json file with variables
问题描述
我有一个json文件,其中包含18个子字符串,如下所示: https://i.stack.imgur.com/aVWuw.png https://i.imgur.com/0ABdcde.png
I have a json file which has 18 substrings like this: https://i.stack.imgur.com/aVWuw.png https://i.imgur.com/0ABdcde.png
但是我有更多的json文件,这些文件具有不同数量的这些子字符串.因此,我这样做是为了查找文本中有多少:
But I have more json files who have different number of these substrings. So I did this to find how many there are in the text:
import json
json_str = open('jsonfile.txt', 'r').read()
contact = json.loads(json_str)
所以GraphImages_total是18 . 每个子字符串都有注释->数据-> 0->所有者->用户名 所以我想打印用户名.
So GraphImages_total is 18 . Every substring has comments --> data --> 0 --> owner --> username So I want to print the username.
comment_author = contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
print(comment_author)
这是针对GraphImages_total = 0 但是我想为所有人做.
This is for GraphImages_total = 0 But I want to do it for all of them.
所以我需要一种使其像这样的方式:
So I need a way to make it like this:
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
推荐答案
contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
^ ^
这表明未知长度的列表在哪里. GraphImages
和data
键保存列表.要遍历列表,请使用for .. in
语句,如下所示:
This indicates where the lists of unknown length are. The GraphImages
and data
keys hold lists. To iterate over a list, you use a for .. in
statement as follows:
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
请注意,您正在直接使用item
.在循环的每个相应迭代中,item
将依次变为'foo'
,'bar'
和'baz'
.您无需使用任何数字索引,也无需计算任何x
或y
.
Note that you're using item
directly. item
will in turn become 'foo'
, 'bar'
and 'baz'
on each respective iteration of the loop. You don't need to use any numeric indices nor count up any x
or y
.
根据您的情况,您需要两个这样的循环:
Applied to your situation, you need two such loops:
for graph_image in contact['GraphImages']:
for comment in graph_image['comments']['data']:
print(comment['text'], comment['owner']['username'])
这篇关于Python检查带有变量的json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!