如何通过Python遍历多个定界的JSON文件?

时间:2019-07-15 07:16:43

标签: python json python-3.x

我面临循环多个分隔的JSON的问题,以下是我的JSON文件内容:

[{"Timestamp":"2019-05-17T18:00:00.19+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"3","Type":"MachineInfo"}}}]]
[{"Timestamp":"2019-05-17T18:00:10.502+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"1","Type":"MachineInfo"}}}]]
[{"Timestamp":"2019-05-17T18:00:05.814+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"9","Type":"MachineInfo"}}}]]

它不起作用,除非我在行工作之后手动添加了逗号(,),如下所示:

[{"Timestamp":"2019-05-17T18:00:00.19+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"3","Type":"MachineInfo"}}}],
{"Timestamp":"2019-05-17T18:00:10.502+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"1","Type":"MachineInfo"}}}],
{"Timestamp":"2019-05-17T18:00:05.814+08:00","Items":[{"Name":"CurrentTaskSequence","Body":{"Status":"9","Type":"MachineInfo"}}}]]
def main():
   #Read json file
    f = open('/home/amirizzat/Desktop/data.json')
    data = json.load(f)
    f.close()
    #Print json
    print(data)

#call main
main()

1 个答案:

答案 0 :(得分:0)

因此,看来您的文件不是完全JSON,而是包含行,每行的内容都是JSON。

您可以做类似的事情

with open('/home/amirizzat/Desktop/data.json') as f:
    data = [json.loads(line) for line in f]

print(data)

这会循环遍历每行,并反序列化JSON,然后将结果放入数组中。