In this blog post, we will explore how to pretty print JSON data in Python, making it more human-readable and easier to work with.
Pretty printing, in the context of JSON, refers to formatting JSON data in a way that makes it easier for humans to read and understand. By default, when you serialize a Python object to JSON using the json module, the resulting JSON data is often compact and not visually appealing. Pretty printing adds indentation and line breaks to make the JSON data more structured and readable.
Using the json Module
Python's built-in json module provides a convenient way to work with JSON data. To pretty print JSON using this module, you first import the json module and then use the json.dumps() function with the indent parameter to specify the level of indentation required.
Here is a sample program:
Note that we have specified a JSON object (“student”) which is not indented in any readable manner. After we use json.dumps and print the result, we get the pretty printed result:
Here is an example of a JSON with multiple levels of nesting:
In this example, we have a JSON object with multiple levels of nesting, including an object (address) and an array (contacts). The indent parameter in json.dumps() is set to 2, which specifies that the JSON should be indented with two spaces for each level of nesting. When you run this code, it will produce nicely formatted JSON with indentation:
This formatted JSON is more human-readable and makes it easier to understand the structure of the data.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.