Pretty print does reading and comprehending a JSON object’s data structure easier. It is beneficial when working with large, complex objects as it provides a more organized view of the data that can be easily navigated and analyzed. Python offers several modules for pretty printing JSON objects, such as JSON, pprint, and simplejson.

The JSON module provides the most basic features for pretty printing JSON objects. It is useful when working with simple JSON objects as it allows you to format and print a given object’s contents easily. The pprint module offers more advanced functions for formatting and printing data structures, making it ideal for those who need to process complex data structures.

Finally, the simplejson module provides additional features such as streaming and integration with other data formats, making it optimal for users who need to work with large amounts of JSON data. By using one of these modules, developers can easily format and print their JSON objects in an organized and readable manner.

No matter the level of complexity of your JSON data, Python’s Pretty Print JSON functionality will help you manage it. With its intuitive design and powerful features, Python can help make data organization as easy as possible. So whether you’re a novice programmer or a seasoned expert, Python’s versatile modules can provide the perfect solution for organizing your data in an easily readable format.

To pretty-print JSON in Python:

  1. Call the json.dumps() method on a JSON object.
  2. Specify the desired number of indentations for each row.

For example:

				
					json.dumps(json_obj, indent=4)
				
			

Where:

  • json_obj is the JSON object you want to pretty-print.
  • indent is the number of indentations, which is commonly 2 or 4.

This is what happens to JSON objects when they are pretty-printed:

Pretty Print JSON

In this guide, you will learn why JSON is often unreadable and how to use pretty-printing to fix the problem.

You will also see some common examples of when pretty-printing can be used. But before learning how to pretty-print JSON, let’s take a quick look at what JSON really is.

What is JSON ?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format used to store and exchange information. It uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value). In addition, JSON is language-independent, making it the ideal choice for applications running on different platforms and systems.

It is a popular data format used by many web services and mobile applications. JSON has become the de facto standard for data exchange, making it easy to read, write, and parse. It is being increasingly used to send data from server-side programming languages to client-side scripts such as JavaScript or Ajax.  The JSON format is also used by programming languages such as PHP, Java, and C++.

The Problem with JSON in Python

JSON stands for JavaScript Object Notation, a data-interchange format that enables data transfer between different applications. Although JSON is widely used in many programming languages, including Python, it has several issues that can cause problems.

One major issue with JSON in Python is its complexity. Because JSON uses text-based data, it can be challenging to parse and interpret the data correctly. Furthermore, JSON requires precise syntax to work properly, making errors more likely. Additionally, because there are so many different formats for storing and accessing data, it can be challenging to ensure that all data is formatted correctly when using JSON.

Python JSON Pretty Printing

There are three common situations when you might want to use pretty-printing:

  1. Pretty-print a JSON object to the console.
  2. Write pretty-printed JSON object to a file.
  3. Read + pretty-print a JSON object into the console.

How to Pretty-Print a JSON String in Python

To pretty-print a JSON string in Python:

  • Call json.loads() to convert the JSON string to a Python object.
  • Use the json.dumps() method to pretty-print the object

The complete syntax of the json.dumps() method is a pretty lengthy multi-parameter call:

				
					json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
				
			

But in this guide and most of the time, all you need to know is this syntax:

				
					json.dumps(obj, indent)
				
			

Where:

  • obj is the JSON object.
  • indent specifies the number of spaces.

If the indent parameter is negative, 0, or an empty string there will be no indentations in the resulting JSON.

By default, the JSON data is not indented and appears in a single line.

Example:

Arrow Function Syntax

				
					import json
 
#Initialize JSON data as a JSON string
json_data = '[ {"name": "David", "topics": ["Python", "Data Structures and Algorithms"]}, \
                 { "name": "Marta", "topics": ["Java", "Functional Programming"]} ]'
 
#Convert JSON to Python object
obj = json.loads(json_data)
 
#Python pretty print JSON
json_formatted_str = json.dumps(obj, indent=4)

print(json_formatted_str)
				
			

Output:

				
					[
    {
        "name": "David",
        "topics": [
            "Python",
            "Data Structures and Algorithms"
        ]
    },
    {
        "name": "Marta",
        "topics": [
            "Java",
            "Functional Programming"
        ]
    }
 ]
				
			

As you can see, the JSON data is now much easier to read. In addition, this formatted JSON is far less confusing than the one-liner version.

How to Write Pretty-Printed JSON String to a File

The json.dump() ​method allows you to write a pretty printed JSON object to a text file using the following syntax:

				
					json.dump(obj, file, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None)
				
			

In this guide, you’ll only be focusing on the obj, file and indent arguments. This will simplify your overall syntax to:

				
					json.dumps(obj, file, indent)
				
			

Where:

  • obj is the JSON object to pretty-printed.
  • file is the file to which you want to pretty-print the JSON.
  • indent is the number of indentations in the JSON data in the new lines.

Example:

				
					#Import json module
import json

#Initialize JSON data as a JSON string
json_data = [{"name": "David", "topics": ["Python", "Data Structures and Algorithms"]},
             {"name": "Marta", "topics": ["Java", "Functional Programming"]}]

#Write pretty print JSON data to file
with open("example.json", "w") as write_file:
    json.dump(json_data, write_file, indent=4)
				
			

This code creates a new file that contains the following:

Pretty Print JSON

As you can see, this file contains neatly organized JSON data. In its current state, the file is easy to read and comprehend.

Read + Pretty-Print a JSON File in Python

Before this point, you have only created JSON objects within your code. However, it is more common that you need to be able to read stored JSON files:

  • On your machine
  • On a web server

To understand how to read and pretty-print JSON data, let’s explore both scenarios.

A. Read a JSON File from Your Machine

To read a JSON object from a file or URL, you can use the json.load() method. To pretty-print the JSON, you can use the json.dumps() method. For example:

				
					import json

with open("example.json", "r") as read_file:
    obj = json.load(read_file)
    print(json.dumps(obj, indent=4))
				
			

Output:

				
					[
     {
         "name": "David",
         "topics": [
             "Python",
             "Data Structures and Algorithms"
         ]
     },
     {
         "name": "Marta",
         "topics": [
             "Java",
             "Functional Programming"
         ]
     }
 ]
				
			

The JSON data looks significantly better this way since the information is structured on different lines rather than everything being crammed together in one line.

B. How to Read a JSON File from a URL in Python

If you want to read a JSON file from a URL and pretty-print it in Python, use the urllib module. If necessary, install urllib by running the following command in your terminal:

				
					pip install urllib
				
			

For example, we can get a list of ToDo items from https://jsonplaceholder.typicode.com/todos . If you open this site using your browser, you will see some JSON data that represents fake ToDo items

Pretty Print JSON

The goal is to show a ToDo JSON object that looks similar in the console.

How to do it:

  • Fetch the contents of a web page with urlopen() function.
  • Load the JSON data from the website content using json.loads() method.
  • Pretty-print the JSON object using the json.dumps() method.

Code:

				
					from urllib.request import urlopen
import json

# Step 1.
response = urlopen("https://jsonplaceholder.typicode.com/todos")

# Step 2.
data_json = json.loads(response.read())

# Step 3.
pretty_json = json.dumps(data_json, indent=4)

print(pretty_json)
				
			

As a result of running this piece of code, you should see a long list of ToDo items.

todo items in Python JSON

Wrap up

Today you learned how to format JSON data in Python so that it is easier to read.

JSON is a text-based data format commonly used and works well with Python. However, to be efficient, JSON data is compressed when sent over the internet, making it difficult to read.

Luckily, a built-in method in Python json.dumps() formats JSON objects and makes them more readable.


Thanks for reading. Happy coding!