The pprint
module can be used to pretty-print the Python data structures in a readable format. The pprint
is a native Python library.
We can use the pprint()
method or create our pprint
object with PrettyPrinter()
.
pprint.pprint(object, stream = None, indent = 1, width = 80, depth = None,compact = False, sort_dicts = True, underscore_numbers = False)
The pprint()
method takes the following parameters:
object
: It is the object to be pretty-printed.stream
: It is a file-like object to which the output is written by calling its write()
method. Its default value is None
. This can be used when we want to write the pretty-print data to a file or a stream.indent
: It denotes the amount of space added for each nesting level. The default value is 1
.width
: It denotes the maximum number of characters per line in the output. If the characters exceed the width, the remaining will be wrapped to the next line. The default value is 80
.depth
: It is the number of depth levels (nested data types) to be displayed. If the depth level of data is beyond the configured depth limit, then ...
will be displayed. By default, it will show all data.compact
: If compact is False
(the default) then each item of a sequence will be formatted on a separate line. If compact is True
, the maximum items that can fit within the width will be formatted on each output line.sort_dicts
: If set to True,
dictionaries will be formatted with their keys sorted. Otherwise, they will display in insertion order. The default value is True
.underscore_numbers
: Integers will be formatted with the _
character for a thousand separators. By default, it will not be displayed. The below code demonstrates how to use the pprint()
method:
import jsonfrom urllib import requestimport pprintresponse = request.urlopen("https://jsonplaceholder.typicode.com/users/2")json_response = response.read()users = json.loads(json_response)print("Without pretty print")print(users)print("With pretty print")pprint.pprint(users)print("With pretty print and depth 1 width 30")pprint.pprint(users, depth = 1, width= 30)
In the above code:
print
method. Note: When using the
pprint()
method to pretty-print the JSON data with depth as 1
and width as 30
.We can configure the default configurations of the pprint
method by creating the new PrettyPrinter()
object. So we can use the object to pretty-print without specifying the configuration on each function call.
import jsonfrom urllib import requestfrom pprint import PrettyPrinterresponse = request.urlopen("https://jsonplaceholder.typicode.com/users/2")json_response = response.read()users = json.loads(json_response)custom_printer = PrettyPrinter(indent=4,width=100,depth=2,compact=True,sort_dicts=False)custom_printer.pprint(users)
In the above code:
PrettyPrinter
object with custom configuration to pretty-print the data. pprint
method of the custom_printer
object to pretty-print the user's data.Free Resources