如何从4GB JSON文件中提取数据?

时间:2016-07-25 10:31:01

标签: python json ijson

我有一个4GB的JSON文件,其结构如下:

{
    rows: [
        { id: 1, names: { first: 'john', last: 'smith' }, dates: ...},
        { id: 2, names: { first: 'tim', middle: ['james', 'andrew'], last: 'wilson' }, dates: ... },
    ]
}

我只想迭代所有行,并为每一行提取ID,名称和其他一些细节,并将其写入CSV文件。

如果我尝试以标准方式打开文件,它就会挂起。我一直在尝试使用IJSON,如下所示:

f = open('./myfile.json')
rows = ijson.items(f, 'rows')
for r in rows:
    print r

这可以在文件的简短摘录中正常工作,但在大文件上,它会永远挂起。

我也尝试过这种IJSON方法,它似乎适用于大4GB文件:

for prefix, the_type, value in ijson.parse(open(fname)):
    print prefix, value

但是这似乎依次打印每个叶子节点,没有每个顶级行的概念作为单独的项目 - 对于具有任意数量的叶子节点的JSON数据,这很快得到。要获得所有名称的数组,我需要做类似的事情:

names = []
name = {}
for prefix, the_type, value in ijson.parse(open(fname)):
    print prefix, value
    name[prefix] = 'value'
    if 'first' in name and 'last' in name and 'middle' in name:
        # This is the last of the leaf nodes, we can add it to our list...
        # except.... how to deal with the fact that middle may not 
        # always be present?
        names.append(name)
        name = {}

在这么大的文件中,有没有办法依次遍历每一行(而不是每一片叶子)?

0 个答案:

没有答案