您需要的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)
如果我不明白你的问题是错误的,似乎有可能编写一个分隔符行,在你写对象之后的每一次迭代中,你的数据不会有像“-----”那样的分隔符,当你看到分隔符时创建一个新对象。 – alpert
啊,我明白了。这绝对有效。我认为可能有其他流处理解决方案。 – CentAu