Compress Json Data Using Gzip and Python

JSON data can exist in two forms: in a file or data saved in a variable stored in memory. This article will show how to compress and decompress JSON data in both formats.

Compressing JSON Data Stored in Python Dictionary Using Gzip

Compressing JSON data using gzip package is done in three steps:

  • Convert the object passed into JSON string. The object must be JSON-serializable,
  • Encode JSON string into bytes,
  • Compress the result using gzip.compress() function.

Here is an example.

Output (truncated):


Then you can decompress the compressed data using gzip.decompress(), as shown below.


[{'Name': 'Allan', 'Registration': 2709, 'Address': 'Chicago', 'Marks': [56, 89, 72]}, {'Name': 'Bob', 'Registration': 2451, 'Address': 'Michigan', 'Marks': None}, {'Name': 'Allan', 'AdRegistrationm': 2709, 'Address': 'Berlin', 'Marks': [82, 88, 65]}]

Compressing JSON Data into a Gzip File

If you have JSON data you want to send to a Gzip file, the following code example should do the job.

You can shorten the code above, as shown below.

Then you can read JSON data from a Gzip file with the following code.

You can also shorten the code above as follows.

Compress an Existing JSON File Using Gzip

This Section shows how to compress a JSON file into a .gz file using gzip module. The following code should serve the purpose.