I am working on a process that will likely end up attempting to serialize very large json arrays to file. So loading up the entire array in memory and just dumping to file won't work. I need to stream the individual items to file to avoid out of memory issues.
Surprisingly, I can't find any examples of doing this. The code snippet below is something I've cobbled together. Is there a better way to do this?
first_item = True
with open('big_json_array.json', 'w') as out:
out.write('[')
for item in some_very_big_iterator:
if first_item:
out.write(json.dumps(item))
first_item = False
else:
out.write("," + json.dumps(item))
out.write("]")