1

在这里,我想将一个“大”字典转储到 json 中,如下所示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import simplejson as json

doc = {}
# appending the doc, so that the doc is more than 2G
.....

json_doc = json.dumps(doc)

然后我收到以下错误消息:

  File "C:\Python27\lib\site-packages\simplejson\__init__.py", line 286, in dump
s
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\site-packages\simplejson\encoder.py", line 228, in encod
e
    chunks = list(chunks)
MemoryError

我该如何解决?谢谢!

4

1 回答 1

5

如果内存不足,您可以尝试将对象增量编码为 json:

import json
import sys

d = dict.fromkeys(range(10))
for chunk in json.JSONEncoder().iterencode(d):
    print(chunk) # print each chunk on a newline for demonstration

不要在字符串中累积输出,使用文件/套接字并立即写入/发送块。

输出

{
"0"
: 
null
, 
"1"
: 
null
, 
"2"
: 
null
, 
"3"
: 
null
, 
"4"
: 
null
, 
"5"
: 
null
, 
"6"
: 
null
, 
"7"
: 
null
, 
"8"
: 
null
, 
"9"
: 
null
}
于 2011-12-29T03:34:52.203 回答