Python Data Pretty Printer

PythonProgrammingServer Side Programming

To print non-trivial data structure in the python console, we can use the pretty printer module. If the object has different texts in single line, this method will break them into separate lines

To use this module, we should import it using.

import pprint

There are different methods related to pretty print. These methods are −

Method pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False)

This method is used to return a formatted representation of object as string. Different information like indent, width, depth all are passed as arguments to perform the task.

Method pprint.pprint(object, stream = None, indent=1, width=80, depth=None, *, compact=False)

This method is used to print the formatted representation of object on stream. When the stream is not specified, sys.stdout is used.

Method pprint.isreadable(object)

This method will check whether the formatted representation of the object is readable or not.

Example Code

import pprint
import json
json_data = json.loads(open('sample_json.json', 'r').read())
print("The JSON Data:")
if pprint.isreadable(json_data):
    print('The Data is Readable')
    print('The Data is Not Readable')
The JSON Data in correct format:") pprint.pprint(json_data)


The JSON Data:
[{'name': 'Subhas', 'age': 25, 'city': 'Kolkata'}, {'name': 'Palash', 'age': 22, 'city': 'Delhi'}, {'name': 'Vivek', 'age': 23, 'city': 'Bangaluru'}]
The Data is Readable

The JSON Data in correct format:
[{'age': 25, 'city': 'Kolkata', 'name': 'Subhas'},
 {'age': 22, 'city': 'Delhi', 'name': 'Palash'},
 {'age': 23, 'city': 'Bangaluru', 'name': 'Vivek'}]
Updated on 30-Jul-2019 22:30:23