Python Pretty Print JSON

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.

Here is an illustration of what pretty printing does to JSON objects:

In this guide, you learn why JSON is usually unreadable and how to use pretty printing to fix the problem. You will also see some common examples when pretty-printing.

Before learning how to pretty-print JSON, let’s take a quick look at what JSON really is.

What is JSON?

JSON stands for JavaScript Object Notation. It is a popular text-based data format used broadly to represent structured data.

JSON is commonly used to transmit data between the client and a server because JSON is nothing but structured text, making it a lightweight data format.

Almost every programming language supports JSON, Python being no exception.

The Problem with JSON in Python

When transmitting data over the internet, you want to be as efficient as possible. A really good starting point is to send as little data as possible.

When sending a JSON object over the internet, the JSON payload is sent in an optimized format to save bandwidth.

The problem with the optimized JSON is it is hard to read. To make the JSON readable, you can use what is called pretty printing.

This guide teaches you how to format your JSON objects in a readable fashion by pretty printing them.

Python JSON Pretty Printing

JSON pretty-printing is possible by using the built-in JSON module in Python.

There are three common situations when you might want to use pretty printing when dealing with JSON:

  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.

Let’s go through each possibility by showing an example.

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 indent is None and the JSON data is represented in a single line.

Let’s see an example:

import json
 
#Initialize JSON data as a JSON string
json_data = '[ {"name": "Jack", "topics": ["Python", "Data Structures and Algorithms"]}, \
                 { "name": "Sofie", "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": "Jack",
        "topics": [
            "Python",
            "Data Structures and Algorithms"
        ]
    },
    {
        "name": "Sofie",
        "topics": [
            "Java",
            "Functional Programming"
        ]
    }
 ]

As you can see, now the JSON data is nicely formatted. This JSON is really easy to read as opposed to the lengthy one-liner JSON.

How to Write Pretty-Printed JSON String to a File

You can write a pretty printed JSON object to a text file using json.dump() method. The complete syntax of the json.dump() method is a rather verbose multi-parameter function call:

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

But in this guide, you only need to focus on the arguments obj, file, and indent. This simplifies the 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.

Let’s take a look at a simple example of pretty printing to a file:

#Import json module
import json

#Initialize JSON data as a JSON string
json_data = [{"name": "Jack", "topics": ["Python", "Data Structures and Algorithms"]},
             {"name": "Sofie", "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)

Running this piece of code results in a new file being created with the following contents:

Python pretty print JSON

As you can tell, this file contains nicely formatted JSON data in it. In this form, the file is easy to read, and understanding the JSON structure is clear.

Read + Pretty-Print a JSON File in Python

So far you’ve only worked with JSON objects that you have created directly in your code.

But commonly, you need to be able to read JSON files stored:

  • On your machine.
  • On a web server.

Let’s see how to read and pretty-print the JSON data in both situations.

1. Read a JSON File from Your Machine

You can read a JSON object from a file or URL with the json.load() method. Then use the json.dumps() method to pretty-print the JSON. 

To demonstrate, let’s read the file you just created in the previous example:

import json

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

Output:

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

Once again, the JSON data looks great this way as the data is spread across the lines in a structured format rather than a single one-liner.

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

You can also read a JSON file from a URL and pretty-print it to the console in Python.

To fetch data behind a URL, use the urllib module. If you don’t have urllib installed on your system, install it by running the following in the command line:

pip install urllib

For instance, let’s fetch a list of ToDo items from https://jsonplaceholder.typicode.com/todos. If you open up this site with your browser, you see a bunch of JSON data that represents dummy ToDo items.

JSON example

Our goal is to show a similar-looking pretty-printed ToDo JSON object in the console.

Here is how to do it:

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

Here’s the 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 pretty printed long list of ToDo items.

JSON pretty-print in Python

Conclusion

Today you learned how to pretty-print JSON data in Python.

To recap, JSON is a commonly used text-based data format that works in Python. To be as efficient as possible, JSON data is compressed when sent over the internet. This compressed format comes at the expense of readability and usually, the JSON is just a lengthy oneliner of nonsense.

To read the JSON data you need to format it in a structured fashion. This is called pretty-printing and is easy in Python with built-in methods. To improve JSON readability, you can pretty-print the JSON object using the json.dumps() method.

Thanks for reading.

Happy coding!

See Also