在 python 中加载 1GB 大 json 文件时如何解决内存错误?
How to solve memory error when loading 1GB large json files in python?
我正在尝试将 json 文件转换为 csv 但出现内存错误。
有什么有效的方法可以微调此代码以处理 python.
中的大型 json 文件
def change(row, pastkeys=()):
result = {}
c=0
for key in row:
c=c+1
newkey = pastkeys + (key,)
print key
val = row[key]
if isinstance(val, dict):
result.update(change(val, newkey))
elif isinstance(val, list):
result.update(change(dict(zip(range(0, len(val)), val)), newkey))
else:
result[newkey] = val
return result
a=open(sys.argv[1],'r')
lines=list(a)
print lines
out1=open(sys.argv[2],'w')
try:
data = json.loads(''.join(lines))
if isinstance(data, dict):
data = [data]
except ValueError:
data = [json.loads(line) for line in lines]
result = []
fields = set()
for row in data:
hash = change(row)
fields |= set(hash.keys()
result.append(hash)
out1=open(sys.argv[2],'w+')
fields = sorted(fields)
out = csv.writer(out1,lineterminator='\n')
out.writerow(['-'.join([str(f) for f in field]) for field in fields])
for row in result:
out.writerow([(row.get(field,'')) for field in fields ])
a.close()
您可以尝试使用 ijson. It is a module that will work with JSON as a stream, rather than a block file. ijson 之于 JSON 就像 SAX 之于 XML。
import ijson
for prefix, theType, value in ijson.parse(open(jsonFileName)):
print prefix, theType, value
您正在将文件的全部内容加载到一个列表(行)中,并将结果存储在另一个列表(结果)中。
除非您需要一些优势,例如访问速度(ram vs hdd),否则不要将文件的全部内容加载到内存中。
相反,您可以一次处理一行,读取它,处理它并附加到您的文件中。
我正在尝试将 json 文件转换为 csv 但出现内存错误。 有什么有效的方法可以微调此代码以处理 python.
中的大型 json 文件def change(row, pastkeys=()):
result = {}
c=0
for key in row:
c=c+1
newkey = pastkeys + (key,)
print key
val = row[key]
if isinstance(val, dict):
result.update(change(val, newkey))
elif isinstance(val, list):
result.update(change(dict(zip(range(0, len(val)), val)), newkey))
else:
result[newkey] = val
return result
a=open(sys.argv[1],'r')
lines=list(a)
print lines
out1=open(sys.argv[2],'w')
try:
data = json.loads(''.join(lines))
if isinstance(data, dict):
data = [data]
except ValueError:
data = [json.loads(line) for line in lines]
result = []
fields = set()
for row in data:
hash = change(row)
fields |= set(hash.keys()
result.append(hash)
out1=open(sys.argv[2],'w+')
fields = sorted(fields)
out = csv.writer(out1,lineterminator='\n')
out.writerow(['-'.join([str(f) for f in field]) for field in fields])
for row in result:
out.writerow([(row.get(field,'')) for field in fields ])
a.close()
您可以尝试使用 ijson. It is a module that will work with JSON as a stream, rather than a block file. ijson 之于 JSON 就像 SAX 之于 XML。
import ijson
for prefix, theType, value in ijson.parse(open(jsonFileName)):
print prefix, theType, value
您正在将文件的全部内容加载到一个列表(行)中,并将结果存储在另一个列表(结果)中。
除非您需要一些优势,例如访问速度(ram vs hdd),否则不要将文件的全部内容加载到内存中。
相反,您可以一次处理一行,读取它,处理它并附加到您的文件中。