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

标签 python json dictionary

我有一个很大的 for 循环,我在其中创建了 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) 之类的东西转储整个列表。我希望能够在每次迭代中将对象附加到文件中。

谢谢。

最佳答案

您需要使用 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
}
]

要逐 block 读取它,您需要使用 JSONDecoder 并将可调用对象作为 object_hook 传递。当您调用 JSONDecoder.decode(json_string)

时,将使用每个新的解码对象(列表中的每个 dict)调用此 Hook

关于Python,将 json/dictionary 对象迭代写入文件(一次一个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827114/

相关文章:

python - 在 python 中更新 Json 值

javascript - 将 Map 复制到现有 Map 的最高效方法

python - 在 linux 中升级 python

python - 生成所有具有字符 a、b 或 c 且长度等于 n 且最多有 1 个 b 和 2 个 c 的字符串

c++ - 如何按 FIFO 顺序对 C++ 映射进行排序?

java - Jackson Mapper 序列化空对象而不是 null

python - 删除 json 输出中具有空值的列

python - 如何通过多个键对数组进行分组?

python - 如何使用 App Engine app.yaml 文件中定义的路由来提供来自 Google Cloud Storage 的内容?

c# - 无法从解决方案访问 IIS Express 文件夹