我正在尝试从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 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
如何打印动作列表中的第二项?
答案 0 :(得分:0)
data [“macros”] [n] [“actions”]是一个列表,但元素数量可变。
要修复它,我需要迭代该数组,然后获取正确的值。
for action in data["macros"][n]["actions"]:
#do stuff here