Pretty-Print JSON and Move It to the Command Line

DZone 's Guide to

Pretty-Print JSON and Move It to the Command Line

Pretty-printing JSON is a very common operation. In this post, I show how to build the code and make the script an executable as a first-class command.

· Web Dev Zone ·
Free Resource

Command Prompt

Building a Pretty Print Program

In Python, pretty-printing is very straight forward. It only needs the use of the built-in JSON library and the use of the dumps method. Given any data, the following code can format and sort the keys of JSON and print it to the console.

import json
json.dumps(json_data, indent=4, sort_keys=True)

Creating Work-Flow

To this single line, we need to add the argsparse code so that it can take input parameters and add a help function as well.

In this code, I have added the ability to:

  • Specify the JSON file that is the input.
  • Specify an optional output file that will contain the formatted JSON. By default, we over-write the incoming JSON file.

That’s pretty much it. There is not much error handling since we don’t really need a lot of it.

The code is available here.

#! /usr/bin/env python
# Author: akshayranganath
# Gihub link: https://github.com/akshayranganath/python_pretty_printer
import json
import argparse

def getFileData(fileName):
		Open a file, and read the contents. The with..open operation will auto-close the file as well.
	with open(fileName) as handle:
		data = handle.read()

	return data

def prettyPrint(data, outfile):
		Pretty print and write the file back to the argument 'outfile'
	with open(outfile, "wb") as handle:
		handle.write ( json.dumps(json.loads(data), indent=4, sort_keys=True) )

if __name__=="__main__":
	parser = argparse.ArgumentParser(description='Pretty print JSON')
	parser.add_argument('--file', help="JSON file. If no --outfile is provided, this file will be over-written",required=True )
	parser.add_argument('--outfile', help="Output file to pretty print the JSON", required=False )

	args = parser.parse_args()        
	outfile = args.file if args.outfile is None else args.outfile

	jsondata = getFileData(args.file)
	prettyPrint(jsondata, outfile)
	print 'Pretty printer complete.'

Converting to a Command Line

Converting this script to a command line is a two step process:

  • Add execute permission.
  • Move code to a folder in the shell PATH.

Add Execute Permission

To give execute permission to the script, simple run this command:

chmod +x pretty_printer.py 

This will provide execute access only for the user running the command. If you want all users on this system to have the execute permission, issue this command instead:

chmod a+x pretty_printer.py 

Making the Script a Command

To make the script work like a regular command, move it to a location that is on the shell’s PATH list. On Linux/Mac, you can get this with the echo command:

echo $PATH 

On Windows systems, execute the set command and look for PATH.

Based on the output, move the pretty_printer.py to a location specified in the PATH directory list. For Linux/Mac users, you could move it to /usr/local/bin. Once done, you can execute this as a built-in command from any folder.

After it is setup correctly, you can execute it like this.

$ pretty_printer.py --file rules.json
Pretty printer complete.
json, python, web dev

Published at DZone with permission of Akshay Ranganath , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}