使用json.dumps()的MemoryError [英] MemoryError using json.dumps()
问题描述
在将大型数组编码为json格式时,我想知道json.dump()
或json.dumps()
哪一个是最有效的.
I would like to know which one of json.dump()
or json.dumps()
are the most efficient when it comes to encoding a large array to json format.
能给我示范一个使用json.dump()
的例子吗?
Can you please show me an example of using json.dump()
?
实际上,我正在制作一个Python CGI,它使用ORM SQlAlchemy从MySQL数据库中获取大量数据,在一些用户触发处理之后,我将最终输出存储在一个数组中,最后将其转换为Json.
Actually I am making a Python CGI that gets large amount of data from a MySQL database using the ORM SQlAlchemy, and after some user triggered processing, I store the final output in an Array that I finally convert to Json.
但是在使用:
print json.dumps({'success': True, 'data': data}) #data is my array
我收到以下错误:
Traceback (most recent call last):
File "C:/script/cgi/translate_parameters.py", line 617, in <module>
f.write(json.dumps(mytab,default=dthandler,indent=4))
File "C:\Python27\lib\json\__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\lib\json\encoder.py", line 209, in encode
chunks = list(chunks)
MemoryError
所以,我的猜测是使用json.dump()
来按块转换数据.有关如何执行此操作的任何想法?
So, my guess is using json.dump()
to convert data by chunks. Any ideas on how to do this?
还是使用json.dump()
以外的其他想法?
Or other ideas besides using json.dump()
?
推荐答案
您只需替换
f.write(json.dumps(mytab,default=dthandler,indent=4))
作者
json.dump(mytab, f, default=dthandler, indent=4)
这应该将数据流式传输"到文件中.
This should "stream" the data into the file.
这篇关于使用json.dumps()的MemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!