Compress large JSON text streams into one indexed zip file

This may help with processing of multiple large JSON files. It creates an indexed zip file containing all JSON files that can then be read with Python.

Compress json stream(s) into indexed compressed format (zip file)
for far more efficient processing


$ python3 /tmp/jsonfile1.json /tmp/jsonfile2.json

import os
import math
import json
import psutil
import sys
import gzip
import bz2
import logging
import argparse
import zipfile

process = psutil.Process(os.getpid())

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', \

logger = logging.getLogger('JsonToZip')

parser = argparse.ArgumentParser(description='Add large json arrays(s) \
    as separate files in one large zip file for efficient indexing')

# Required positional argument
parser.add_argument('input_files', type=str, nargs='+',
                    help='Input json file(s) in order (bz2 or gz also \
parser.add_argument('--encoding', type=str, default='UTF-8',
                    help='Input text file encoding (default: "UTF-8")')
#parser.add_argument('--compression', type=str, default='none',
#                    help='Zip compression: "none", "gzip", "lzf" \
#                    (default: "none")')

args = parser.parse_args()
assert len(args.input_files) > 0

#assert args.compression in ['none', 'gzip', 'lzf']

#if args.compression == 'none':
#    args.compression = None

outputFn = args.input_files[0] + '.zippack'

lastData = ''
lastPrintedProgress = 0
dataCount = 0

# nothing special: just return the data string as-is for now
processData = lambda doc: doc'Creating zip file %s' % outputFn)

zf = zipfile.ZipFile(outputFn, 

file_count = len(args.input_files)'Beginning input file iteration...')

for file_idx, input_file in enumerate(args.input_files):'Open input file: %s' % input_file)

    if input_file.lower().endswith('.bz2'):
        infile =, 'rt', encoding=args.encoding)
    elif input_file.lower().endswith('.gz'):
        infile =, 'rt', encoding=args.encoding)
        infile = open(input_file, 'r', encoding=args.encoding)

        infilename = input_file.split('/')[-1]
        infilename = input_file.split('\\')[-1]'Decoding JSON...')
    jsondata = json.loads(

    rss = process.memory_info().rss / 1048576.0
    sys.stderr.write( \
        '\rDump data: FILE=%s, IDX=%d, COUNT=%d/%d (%.2f%%), ' \
        'MEM=%.2fMB' % \
        (infilename, dataCount+1, file_idx+1, \
        file_count, 100.0 * (file_idx+1)/file_count, rss))

    for record_idx, record in enumerate(jsondata):
        data_to_save = json.dumps(record)
        zf.writestr('%d.json' % dataCount, data_to_save)
        dataCount += 1

zf.writestr('datacount', str(dataCount))

sys.stderr.flush()'File iteration complete.')

zf.close()'Output %d objects to %s' % (dataCount, outputFn))


Test the zip file:

import json
import zipfile

zf = zipfile.ZipFile('', 'r')


Leave a Reply

Your email address will not be published. Required fields are marked *