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

Cen*_*tAu 9 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) 
Run Code Online (Sandbox Code Playgroud)

stream_dump 是我想要的功能.

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

谢谢.

mem*_*tum 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)
Run Code Online (Sandbox Code Playgroud)

输出继电器:

[
{
"my_1"
:
1
}
,
{
"my_2"
:
2
}
,
{
"my_3"
:
3
}
,
{
"my_4"
:
4
}
]
Run Code Online (Sandbox Code Playgroud)

要按块读取块,你需要使用JSONDecoder并传递一个可调用的object_hook.dict当您调用时,将使用每个新的解码对象(列表中的每个对象)调用此挂钩JSONDecoder.decode(json_string)