我有一个JSON文件,其中包含以下内容
[
{"ID": 1, "timestamp": 10, "startingFloor": 1, "eventType": "enter"},
{"ID": 1, "timestamp": 10, "eventType": "call", "noOfCalls": 1},
{"ID": 1, "timestamp": 10, "startingFloor": 1, "eventType": "board"},
{"ID": 1, "timestamp": 10, "eventType": "weight", "currentLoad": 53},
{"ID": 1, "timestamp": 36, "eventType": "call", "noOfCalls": 2},
{"ID": 2, "timestamp": 50, "eventType": "call", "noOfCalls": 3},
{"ID": 2, "timestamp": 15, "eventType": "call", "noOfCalls": 1},
{"ID": 2, "timestamp": 38, "eventType": "weight", "currentLoad": 84},
{"ID": 2, "timestamp": 27, "eventType": "call", "noOfCalls": 2},
{"ID": 2, "timestamp": 36, "startingFloor": 2, "eventType": "enter"},
{"ID": 3, "timestamp": 50, "startingFloor": 3, "eventType": "enter"},
{"ID": 4, "timestamp": 38, "startingFloor": 4, "eventType": "board"},
{"ID": 4, "timestamp": 27, "startingFloor": 4, "eventType": "enter"},
{"ID": 5, "timestamp": 15, "startingFloor": 5, "eventType": "enter"}
]
我需要能够将这个文件的每一行拉出来与它进行交互,类似于字典(对于一个非常简单的例子,我需要找到最高的noOfCalls值)。
问题是该文件是一系列JSON对象,因此以前使用的JSON文件的常规方法不起作用,例如;
with open('input.json') as data_file:
data = json.load(data_file)
我尝试过其他方法,例如尝试拉出每个对象并将其附加到列表中,例如:
data = []
for line in open('input.json','r'):
data.append(json.loads(line))
但是这个版本也没有。
我也尝试了其他各种方法,但总是会出现“额外数据”,“期望值”等错误。
任何有关从单个文件解析多个JSON对象的信息都会非常感激,因为没有更多的代码示例而道歉,因为我尝试过的很多尝试都被替换了。
答案 0 :(得分:2)
试试这个:
with open('input.json') as data_file:
data = json.loads(data_file.read())
答案 1 :(得分:1)
似乎对我有用
import json
with open('input.json') as fr:
data = json.loads(fr.read())
for line in data:
if 'noOfCalls' in line :
print line['noOfCalls']