Making A Python JSON Minify Tool

Making A Python JSON Minify Tool

Python makes writing portable command line tools easier. It is installed on many different operating systems by default and has a huge standard library to work with. So, today we’re going to write a JSON minification tool to remove white space, going from requirements, adding libraries and finally walking through the code.

 

Requirements

 

Adding Libraries

These lines are important to any of your Python programs. The first line is the shebang  line.

The shebang line allows users to execute the Python program without typing: Python 3 <File Name> on Linux and Mac. It tells the computer what interpreter to use on the program/script. Next are the import statements.

The import statements are used to add libraries into your Python program. The libraries we’re using are sys (system library), json (JSON library), and Libraries offer us a lot of power without relying too heavily on third parties. Now, that we’re done importing let’s discuss the code line by line.

 

JSON Minify Code

Here’s the source code:

 

On the first line, we create a function called minify that takes one param file_name. Next, we take the file_name and open the file for reading, reading the data into our program as a string. Then we call json.loads on the data to format it as a json object, then json.dumps with separators set with no whitespace to keep it compact. Finally, we format the filename and remove the .json extension to create a new "<filename>_minify.json" Now, we can call the function.

We call the function using arguments passed from the command line which is contained in sys.argv . We then use a for loop to go through each argument supplied and minify the json file. Here’s an example JSON file to use:

 

In the console

Here’s the output of the program after minifying the json file:

This completes our script and brings us to some conclusions.

Python allows us to write code fast with few dependencies. Unlike languages like Javascript, there are very few tools required for getting started on any project. This makes a lot of choices easy in what tools to use, making Python a great language for prototyping and keeping dependencies low on your project.

Leave a Reply

Your email address will not be published.