我的 JSON 文件中有以下数据:
{
"first": {
"name": "James",
"age": 30
},
"second": {
"name": "Max",
"age": 30
},
"third": {
"name": "Norah",
"age": 30
},
"fourth": {
"name": "Sam",
"age": 30
}
}
我想按如下方式打印顶级键和对象:
import json
import ijson
fname = "data.json"
with open(fname) as f:
raw_data = f.read()
data = json.loads(raw_data)
for k in data.keys():
print k, data[k]
输出:
second {u'age': 30, u'name': u'Max'}
fourth {u'age': 30, u'name': u'Sam'}
third {u'age': 30, u'name': u'Norah'}
first {u'age': 30, u'name': u'James'}
到目前为止,一切都很好。但是,如果我想为一个大文件做同样的事情,我将不得不在内存中读取它。这非常慢并且需要大量内存。
我想使用增量 JSON 解析器(ijson
在这种情况下)来实现我之前描述的:
上面的代码取自:No access to top level elements with ijson?
with open(fname) as f:
json_obj = ijson.items(f,'').next() # '' loads everything as only one object.
for (key, value) in json_obj.items():
print key + " -> " + str(value)
这也不合适,因为它还会读取内存中的整个文件。这并不是真正的增量。
如何在 Python 中对 JSON 文件的顶级键和相应对象进行增量解析?