Pretty print is a helpful mechanism to display any form of data in an easy-readable structure or format. We can do the same with JSON files also. Now, you might ask, what is JSON? In this article, you will learn about JSON and how to pretty print a JSON data through different ways using Python?
What is JSON?
JSON stands for JavaScript Object Notation, is an open-standard file format used explicitly for data interchange. It can store human-readable text. We can access and use it, transmit data objects as attribute-value pairs and arrays. Developers use JSON format to exchange data between servers & client software applications. Python renders a pre-defined JSON module for producing JSON-based operations and tasks.
Pretty Print JSON using Python:
Whenever any application dumps a set of data from any application into Dictionary applying the inbuilt module “json”, the stored result is the same as the dictionary format that distorts JSON's readability. Using Pretty print, we can bring back the JSON format and present the stored JSON data into a presentable format. Let us now see the different methods we can use to pretty print a JSON file in Python.
1: The Indent parameter within json.dumps():
Using the JSON module, we can use the json.dumps() method and passing the json object and indent as parameter by assigning a value. We can also assign special string literals as indent values instead of numbers. If you simply assign 0 as the indent value, it will put a new line to structure your JSON data.
Syntax:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, allow_nan=True, cls=None, indent=<value>, separators=None, default=None, sort_keys=False)
Program:
import json
jsonDict_content = '[{"Employee ID":101, "Name":"Karlos", "Designation":"Sr. Security Engineer"},' \
'{"Employee ID":102, "Name":"Deeza", "Designation" : "Cloud Architect"}]'
json_obj = json.loads(jsonDict_content)
# for indentation level two
print(json.dumps(json_obj, indent = 2))
# for indentation level four
print(json.dumps(json_obj, indent = 4))
# for indentation with 8 spaces gap
print(json.dumps(json_obj, indent = '\t'))
Output:
[
{
"Employee ID": 101,
"Name": "Karlos",
"Designation": "Sr. Security Engineer"
},
{
"Employee ID": 102,
"Name": "Deeza",
"Designation": "Cloud Architect"
}
]
[
{
"Employee ID": 101,
"Name": "Karlos",
"Designation": "Sr. Security Engineer"
},
{
"Employee ID": 102,
"Name": "Deeza",
"Designation": "Cloud Architect"
}
]
[
{
"Employee ID": 101,
"Name": "Karlos",
"Designation": "Sr. Security Engineer"
},
{
"Employee ID": 102,
"Name": "Deeza",
"Designation": "Cloud Architect"
}
]
Explanation:
First, you need to import the json module. Now, you can create a dictionary containing details about two employees. Next, you have to create a JSON object where you will load the dictionary. Now, use the json.dumps() method to convert a Python object into a json string. Within this method, we have passed the json object created a LOC before along with the indent value. The indent value sets the indentation for the json file. We can also assign special string literals as the indent value.
2. Using simplejson.dump() Method:
There is another module that developers can use for pretty print JSON data. Using simplejson module, you can use its simplejson.dumps() method and pass the json object and indent value as parameters. It works similar to that of json module but is not a built-in module of Python.
Install this module before using it
$ pip install simplejson
Program:
import json
import simplejson
jsonDict_content = '[{"Employee ID":101, "Name":"Karlos", "Designation":"Sr. Security Engineer"},' \
'{"Employee ID":102, "Name":"Deeza", "Designation" : "Cloud Architect"}]'
json_obj = json.loads(jsonDict_content)
# for indentation level two
print(simplejson.dumps(json_obj, indent = 2))
Output:
[
{
"Employee ID": 101,
"Name": "Karlos",
"Designation": "Sr. Security Engineer"
},
{
"Employee ID": 102,
"Name": "Deeza",
"Designation": "Cloud Architect"
}
]
Explanation:
Here you have to install the simplejson module and then import it into your program. Now, you can create a dictionary (jsonDict_content) containing details about two employees. Next, you have to create a JSON object where you will load the dictionary. Now, use the simplejson.dumps() method to convert your Python object into a JSON string format. This method also takes a json object along with the value of the indentation.
3. Using pprint.pprint() method:
This is another popular and common practice to pretty print any JSON data in Python code. Python has another pre-defined module pprint that you can import for pretty printing your JSON data. Its pprint() method allows developers to print a formatted structure of your JSON data. The pprint module has a PrettyPrinter class whose constructor help in formatting the JSON data.
Syntax:
pprint.PrettyPrinter(indent, width, depth, stream, compact)
pprint() is a method of pprint module that displays the formatted representation of PrettyPrinter object.
Program:
import json
import pprint
with open("Thisisajsonfile.json", "r") as rd_f:
empl = json.load(rd_f)
print("Before performing the Pretty Print on JSON Data")
print(empl)
print("\n \n")
printData = pprint.PrettyPrinter(indent = 3, width = 75, compact = False)
print("Pretty Printing JSON Data using pprint module")
printData.pprint(empl)
Explanation:
Here, you have to import two modules: json and pprint. Now, take your JSON file (in this case, the JSON file is: Thisisajsonfile.json) and open it in the read mode. Next we load the json. Now we first print the data without json formatting. Next we use the pprint.PrettyPrinter() constructor that allows us to set the indent, width, con=compact, etc. Lastly, we use the pprint() method to pretty print our data in a JSON format.
4. Using pprintjson Module:
pprintjson is another module that has built-in function to pretty print any JSON file. It is not a pre-defined module and hence we need to install it.
Install this module before using it:
$ pip install pprintjson
It’s ppjson() function can pretty print your JSON data in a proper readable format.
Program:
from pprintjson import pprintjson as ppjson
obj = {"a": 1, "b": "string", "c": True}
ppjson(obj)
Output:
{
←[94m"a"←[39;49;00m: ←[34m1←[39;49;00m,
←[94m"b"←[39;49;00m: ←[33m"string"←[39;49;00m,
←[94m"c"←[39;49;00m: ←[34mtrue←[39;49;00m
}
Explanation:
First, you have to install the pprintjson module and then import it into your program. Now, you can create a dictionary (obj). Now, you can simply use the ppjson() function to pretty print our data in a JSON format. It comes as a part of the pprintjson module.
Conclusion:
All these four procedures to pretty print data into JSON format seem handy. But, some of them have their slight setback. The json.dump() and pprint.pprint() are two most preferable techniques because, you don't have to install any module to make them work. On the other hand, simplejson.dump() and ppjson() requires modules to install, which makes them less useful. Now, among json.dump() and pprint.pprint()
, json.dump is easier to use whereas pprint() requires another contructor() to implement for setting the width and indentation.