遍历JSON-列表索引上的typeError

时间:2018-10-16 09:08:54

标签: python json

在尝试遍历JSON对象时遇到了一个奇怪的“广播”问题。一旦迭代值达到100,脚本就会出错,并抱怨键值必须是整数。

import json
#from pprint import pprint

with open('/tmp/myfile.json') as f:
    data = json.load(f)
line_entries = len(data)
len_w = len(data[0]["w"])
#print(line_entries)
line_iter = 0
main_iter = 0
sub_iter = 0
while line_iter < line_entries:
    v = data[line_iter]["v"]["h"]
    c = data[line_iter]["v"]["d"]
    print("=========================================================")
    print("Dest: ", v)
    print("Cart: ", c)

    while sub_iter < len_wp:
        sn = data[line_iter]["w"][sub_iter]["s"]["n"]
        at = data[line_iter]["w"][sub_iter]["at"]
        dt = data[line_iter]["w"][sub_iter]["dt"]
        sub_iter = sub_iter + 1
        print(sn)
        print(at)
        print(dt)
    line_iter = line_iter + 1
    print("=========================================================")

该脚本可以打印出0到99的记录,但是从100可以看到:

v = data[line_iter]["v"]["h"]
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:1)

JSON对象可能包含列表或字典等。只要您有字典,就可以通过示例中的"v"之类的字符串类型的键来访问它,但这不适用于列表。因此,我的猜测是记录100具有列表的类型。