Python 尝试打印JSON列表元素[data][i]name[1]值时,列表索引超出范围
我试图从一个JSON文件将几个值写入CSV,但是得到一个索引超出范围的错误 当我打印行时,它工作,但不在for循环中。这项工作:Python 尝试打印JSON列表元素[data][i]name[1]值时,列表索引超出范围,python,json,Python,Json,我试图从一个JSON文件将几个值写入CSV,但是得到一个索引超出范围的错误 当我打印行时,它工作,但不在for循环中。这项工作: print(data["macros"][0]["actions"][1]["value"]) 但不是这个: #Import the list of email addresses from a file json_data=open('macros.json').read() data = json.loads(json_data) print "Number
print(data["macros"][0]["actions"][1]["value"])
但不是这个:
#Import the list of email addresses from a file
json_data=open('macros.json').read()
data = json.loads(json_data)
print "Number of macros:" + str(numbers) + "\n"
for n in range(0, numbers):
print "\nN at top of loop: " + str(n) + "\n"
name = (data["macros"][n]["title"])
comment = (data["macros"][n]["actions"][1]["value"])
print "\nN: " + str(n) + "\n"
line = "'"+ name + "','" + comment + "'\n"
print line
file.write(line)
#Now go back to the for loop and grab another macro to write out
print "\nN at bottom: " + str(n) + ":\n"
file.close
有趣的是,它确实打印出记录0的第一个标题和值,但当它变为1时,我得到了错误:
N at top of loop: 1
Traceback (most recent call last):
File "./import-json.py", line 55, in <module>
comment = (data["macros"][n]["actions"][1]["value"])
IndexError: list index out of range
循环顶部的N:1
回溯(最近一次呼叫最后一次):
文件“/import json.py”,第55行,在
注释=(数据[“宏”][n][“操作”][1][“值”])
索引器:列表索引超出范围
如何打印操作列表中的第二项?数据[“宏”][n][“操作”]是一个列表,但元素数量可变
要修复它,我需要迭代该数组,然后获取正确的值
for action in data["macros"][n]["actions"]:
#do stuff here
Hi这意味着当n=1时,缺少一个元素。在本例中,它是数据[“宏”][n][“操作”]iYes中的列表,这是正确的,尽管我有点困惑。我需要首先迭代操作列表,然后获取正确的列表元素<代码>用于数据[“宏”][n][“操作”]: