Python,迭代地将json / dictionary对象写入文件(一次一个)

时间:2016-04-24 18:21:12

标签: python json dictionary

我有一个很大的for loop,我在其中创建了json对象,我希望能够将每次迭代中的对象流写入文件。我希望以后能够以类似的方式使用该文件(一次读取一个对象)。 我的json对象包含换行符,我不能将每个对象转储为文件中的一行。 我怎样才能做到这一点?

为了使其更具体,请考虑以下事项:

for _id in collection:
    dict_obj = build_dict(_id)  # build a dictionary object 
    with open('file.json', 'a') as f:
        stream_dump(dict_obj, f) 

stream_dump是我想要的功能。

请注意,我不想创建大型列表并使用json.dump(obj, file)之类的内容转储整个列表。我希望能够在每次迭代中将对象附加到文件中。

感谢。

3 个答案:

答案 0 :(得分:5)

您需要使用JSONEncoder的子类,然后代理build_dict函数

from __future__ import (absolute_import, division, print_function,)
#                        unicode_literals)

import collections
import json


mycollection = [1, 2, 3, 4]


def build_dict(_id):
    d = dict()
    d['my_' + str(_id)] = _id
    return d


class SeqProxy(collections.Sequence):
    def __init__(self, func, coll, *args, **kwargs):
        super(SeqProxy, *args, **kwargs)

        self.func = func
        self.coll = coll

    def __len__(self):
        return len(self.coll)

    def __getitem__(self, key):
        return self.func(self.coll[key])


class JsonEncoderProxy(json.JSONEncoder):
    def default(self, o):
        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, o)


jsonencoder = JsonEncoderProxy()
collproxy = SeqProxy(build_dict, mycollection)


for chunk in jsonencoder.iterencode(collproxy):
    print(chunk)

输出继电器:

[
{
"my_1"
:
1
}
,
{
"my_2"
:
2
}
,
{
"my_3"
:
3
}
,
{
"my_4"
:
4
}
]

要按块读取块,您需要使用JSONDecoder并将可调用传递给object_hook。当您致电dict

时,将使用每个新的解码对象(列表中的每个JSONDecoder.decode(json_string))调用此挂钩

答案 1 :(得分:3)

由于您自己生成文件,因此您只需在每行写出一个JSON对象:

for _id in collection:
    dict_obj = build_dict(_id)  # build a dictionary object 
    with open('file.json', 'a') as f:
        f.write(json.dumps(dict_obj))
        f.write('\n')

然后通过遍历行读取它们:

with open('file.json', 'r') as f:
    for line in f:
        dict_obj = json.loads(line)

这不是一个很好的通用解决方案,但如果你既是发电机又是消费者,那么这个解决方案很简单。

答案 2 :(得分:-2)

最简单的解决方案:

从json文档中删除所有空格字符:

import string

def remove_whitespaces(txt):
    """ We shall remove all whitespaces"""
    for chr in string.whitespace:
        txt = txt.replace(chr)

显然你也可以json.dumps(json.loads(json_txt))(顺便说一句,这也验证了文本是有效的json)。

现在,您可以将文档写入每行一行的文件。

第二个解决方案:

创建[AnyStr] Io流,在Io中写入有效文档,(您的文档是对象或列表的一部分),然后将io写入文件(或将其上传到云端)。