Python 3 Script to Minify or Compress JSON File Using JSON Module Full Project For Beginners

Python 3 Script to Minify or Compress JSON File Using JSON Module Full Project For Beginners

 

Welcome folks today in this blog post we will be minifying or compressing json file using json module in python. All the full source code of the application will be given below.

 

 

 

Get Started

 

 

 

In order to get started you need to install the following library inside your python project using the pipcommand

 

pip install json

 

After installing this library you need to make an app.py file and copy paste the following code

 

app.py

 

 

import json # import json library
import sys # import sys library

def minify(file_name):
    "Minify JSON"
    file_data = open(file_name, "r", 1).read() # store file info in variable
    json_data = json.loads(file_data) # store in json structure
    json_string = json.dumps(json_data, separators=(',', ":")) # Compact JSON structure
    file_name = str(file_name).replace(".json", "") # remove .json from end of file_name string
    new_file_name = "{0}_minify.json".format(file_name)
    open(new_file_name, "w+", 1).write(json_string) # open and write json_string to file


ARGS = sys.argv[1:] # get arguments passed to command line excluding first arg
for arg in ARGS: # loop through arguments
    minify(arg)

 

See also  Python 3 Script to Validate Hexadecimal Color Code Using Regular Expression Full Project For Beginners

 

Now you can run this python script by executing the below command here we will be providing one additional command line argument as the path of the input json file as shown below

 

python app.py input.json

 

So here input.json is the original json file which is not compressed just create this file inside the root directory and copy paste the following code to it

 

input.json

 

[
  {
    "name": "gautam",
    "age": 13,
    "subject": "computer science"
  },
  {
    "name": "gautam",
    "age": 13,
    "subject": "computer science"
  },
  {
    "name": "gautam",
    "age": 13,
    "subject": "computer science"
  },
  {
    "name": "gautam",
    "age": 13,
    "subject": "computer science"
  }
]

 

 

Now after completion of the command it will create the compressed or minified output file as shown below

 

 

 

 

 

 

Leave a Reply