python - 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
解决方案
contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
^ ^
这表明未知长度的列表在哪里。和GraphImages
键data
保存列表。要遍历列表,请使用for .. in
如下语句:
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
请注意,您正在item
直接使用。item
将依次变为'foo'
,'bar'
和'baz'
在循环的每个相应迭代中。您不需要使用任何数字索引,也不需要计算任何x
or y
。
应用于您的情况,您需要两个这样的循环:
for graph_image in contact['GraphImages']:
for comment in graph_image['comments']['data']:
print(comment['text'], comment['owner']['username'])
推荐阅读
- r - 就时间序列的偏差校正而不是 nc 数据而言,在包 hyfo 中出现错误
- asp.net-mvc - 格式异常:输入不是有效的 base-64 字符串,因为它包含非 base 64 字符
- asynchronous - 使用 SetTimeout Vuex Action 重构为异步
- sql - 如何从sql select中排除某些行
- php - 用php编写的库中的函数列表
- sql - 如果一列中的值相同,则连接三行
- php - 我想做,在提交按钮上做 2 个表单动作
- python - 如何使用 django 压缩器访问 node_modules?
- java - Google Play 游戏服务:编写保存的游戏
- vue.js - 我们还需要为每个组件提供一个“key”vuejs