我正在尝试使用 ijson 包解析一个大型 (~100MB) json 文件,这使我能够以高效的方式与文件进行交互。然而,在编写了一些这样的代码之后,
with open(filename, 'r') as f:
parser = ijson.parse(f)
for prefix, event, value in parser:
if prefix == "name":
print(value)
我发现代码只解析文件的第一行而不解析文件中的其余行!!
这是我的 json 文件的一部分:
{"name":"accelerator_pedal_position","value":0,"timestamp":1364323939.012000}
{"name":"engine_speed","value":772,"timestamp":1364323939.027000}
{"name":"vehicle_speed","value":0,"timestamp":1364323939.029000}
{"name":"accelerator_pedal_position","value":0,"timestamp":1364323939.035000}
在我看来,我认为ijson
只解析一个json对象。
有人可以建议如何解决这个问题吗?
最佳答案
由于提供的 block 看起来更像是一组行,每行组成一个独立的 JSON,因此应该对其进行相应的解析:
# each JSON is small, there's no need in iterative processing
import json
with open(filename, 'r') as f:
for line in f:
data = json.loads(line)
# data[u'name'], data[u'engine_speed'], data[u'timestamp'] now
# contain correspoding values
关于python - 使用 python ijson 读取包含多个 json 对象的大型 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200302/