fan*_*yna 8 python json dictionary
我正在编写一个程序,它要求我生成一个非常大的json文件.我知道传统的方法是使用转储字典列表json.dump(),但是列表太大了,甚至总内存+交换空间也无法在转储之前保留它.无论如何将它流式传输到json文件中,即将数据json逐步写入文件中?
Wer*_*mit 16
我知道这是迟了一年,但问题仍然存在,我很惊讶json.iterencode()没有被提及.
iterencode在这个例子中,潜在的问题是你希望通过使用生成器对大数据集进行迭代处理,而json编码不会序列化生成器.
解决这个问题的方法是子类列表类型并覆盖__iter__魔术方法,以便您可以生成生成器的输出.
以下是此列表子类的示例.
class StreamArray(list):
"""
Converts a generator into a list object that can be json serialisable
while still retaining the iterative nature of a generator.
IE. It converts it to a list without having to exhaust the generator
and keep it's contents in memory.
"""
def __init__(self, generator):
self.generator = generator
self._len = 1
def __iter__(self):
self._len = 0
for item in self.generator:
yield item
self._len += 1
def __len__(self):
"""
Json parser looks for a this method to confirm whether or not it can
be parsed
"""
return self._len
Run Code Online (Sandbox Code Playgroud)
从这里开始使用非常简单.获取生成器句柄,将其传递给StreamArray类,将流数组对象传递给iterencode()迭代块并迭代.块将是json格式输出,可以直接写入文件.
用法示例:
#Function that will iteratively generate a large set of data.
def large_list_generator_func():
for i in xrange(5):
chunk = {'hello_world': i}
print 'Yielding chunk: ', chunk
yield chunk
#Write the contents to file:
with open('/tmp/streamed_write.json', 'w') as outfile:
large_generator_handle = large_list_generator_func()
stream_array = StreamArray(large_generator_handle)
for chunk in json.JSONEncoder().iterencode(stream_array):
print 'Writing chunk: ', chunk
outfile.write(chunk)
Run Code Online (Sandbox Code Playgroud)
显示产量和写入的输出连续发生.
Yielding chunk: {'hello_world': 0}
Writing chunk: [
Writing chunk: {
Writing chunk: "hello_world"
Writing chunk: :
Writing chunk: 0
Writing chunk: }
Yielding chunk: {'hello_world': 1}
Writing chunk: ,
Writing chunk: {
Writing chunk: "hello_world"
Writing chunk: :
Writing chunk: 1
Writing chunk: }
Run Code Online (Sandbox Code Playgroud)
遗憾的是,该json库没有任何增量写入设施,因此无法执行您想要的操作。
这显然将是一个非常大的文件 - 其他一些表示形式会更合适吗?
否则,我能提出的最好建议是将每个列表条目转储到内存结构中,并使用必要的分隔符([在开头、],[条目之间和]结尾处)将它们写出,以尝试构建您需要的 JSON。
如果格式很重要,您应该知道程序编写的包装器测试将破坏正确的缩进,但缩进仅适用于人类,因此它不会对 JSON 结构的语义产生任何影响。