Skip to content

Pretty Print a JSON File in Python (6 Methods)

Pretty Print a JSON File in Python (5 Methods) Cover Image

In this tutorial, you’ll learn how to use Python to pretty print JSON. When you get a JSON file or down some JSON from an API, it will usually be in a minified version in order to save bandwidth.

But, for reading the JSON or for debugging, it can often be easier to print out the JSON in a more structured format. Pretty printing means having proper line breaks, indentation, white space, and overall structure.

By the end of this tutorial, you’ll have learned:

  • How to pretty print a JSON object in Python
  • How to pretty print a JSON file using Python
  • How to pretty print a JSON file using the pprint module
  • How to sort keys in a JSON file while pretty printing
  • How to save a pretty printed JSON object to a file

The Quick Answer: Use json.dumps() to pretty print JSON

Quick Answer - Python Pretty Print JSON
How to pretty print a JSON object in Python

What is JSON?

JSON stands for JavaScript Object Notation. While it contains the name JavaScript, don’t be alarmed! In this tutorial, we’ll be using Python to manipulate a JSON file. JSON is a lightweight data-interchange format that is easy for machines to read and write, but also easy for humans to understand.

When you look at a JSON file, you’ll likely notice how similar JSON really is to a Python dictionary. In fact, this is true for many other languages, making JSON a great data interchange format. JSON will contain a key and a value for each pair, separated by commas. A value can also be a list (or array) of items, or another dictionary-like object.

Let’s take a look at what we mean by pretty printing JSON in Python. Typically, JSON will come in a minimized form in order to save bandwidth when downloading it. Because of this, it will often look something like this:

{"activity":"Plan a trip to another country","type":"recreational","participants":1,"price":0,"link":"","key":"5554727","accessibility":0}

When we want to pretty print a JSON file, we mean to add appropriate structure, indenting, whitespace, etc. Our above example would then look like this:

{
  "activity": "Plan a trip to another country",
  "type": "recreational",
  "participants": 1,
  "price": 0,
  "link": "",
  "key": "5554727",
  "accessibility": 0
}

Now that you know what a pretty-printed JSON file looks like, let’s see how we can pretty print a JSON file in Python.

How to Pretty Print a JSON File in Python

Let’s take a look at how you can pretty print a JSON file using Python. If you don’t have a JSON file of your own or just want to follow along with the tutorial line by line, I have provided a sample JSON file. You can down the file here, by simply clicking “Save As” on the link here.

Our first step will be to read the JSON file. We can accomplish this by using a context manager to load the file. Let’s see how we can do this in Python:

# Reading a JSON File with a Context Manager in Python
import json
file_path = "/Users/nikpi/Desktop/sample.json"

with open(file=file_path, mode='r') as read_file:
    object = json.load(read_file)
    print(object)

# Returns: {'activity': 'Plan a trip to another country', 'type': 'recreational', 'participants': 1, 'price': 0, 'link': '', 'key': '5554727', 'accessibility': 0}

Let’s break down what we did above:

  1. By using the with keyword, Python manages some of the resourcing of opening the file for us.
  2. We can then, as shown above, use the alias we assign, read_file, in the indented portion of our code.
  3. We use the json.load() function to load the file to a Python dictionary.
  4. When we print out the file, we can see that it’s printed out as the minimized, flat version of JSON code.

The json library comes with a function, dumps(), which allows you to dump the object as a string. One of the parameters of the function allows us to customize the indent that we want our JSON object to be indented with.

Let’s see how we can print it out in a more structured format using the json_dumps() method:

import json
file_path = "/Users/nikpi/Desktop/sample.json"

with open(file=file_path, mode='r') as read_file:
    object = json.load(read_file)
    pretty_object = json.dumps(object, indent=4)
    print(pretty_object)

# Returns:
# {
#     "activity": "Plan a trip to another country",
#     "type": "recreational",
#     "participants": 1,
#     "price": 0,
#     "link": "",
#     "key": "5554727",
#     "accessibility": 0
# }

Let’s explore what we did here:

  1. We load our file path to a file_path variable. If you’re using Windows, it can be helpful to prefix your string with an r to load it as a raw string, to prevent accidental escaping with backslashes.
  2. We then use a context manager to read our file (this is indicated by mode='r')
  3. We load our JSON object using the json.load() method
  4. We then dump this object into a string using the .dumps() method, specifying the number of spaces we want to use to indent our JSON
  5. Finally, we print the file and it’s looking much, much prettier!

In the following section, you’ll learn how to use Python to pretty JSON data that you get back from an API.

How to Pretty Print JSON From an API in Python

Many times when you’re working with JSON in Python, it’ll be via an API using the requests library. Let’s make use of the Bored API to load a sample JSON file. To do this, we’ll import requests to handle calling the API.

Let’s take a look at how we can use an HTTP GET request to fetch data from the API endpoint.

# Loading and Serializing Data From an API
import requests
import json

response = requests.get("https://www.boredapi.com/api/activity")
print(response.json())

# Returns: {'activity': "Clean out your closet and donate the clothes you've outgrown", 'type': 'charity', 'participants': 1, 'price': 0, 'link': '', 'key': '9026787', 'accessibility': 0.1}

In the example above we:

  1. Imported both the requests and json libraries
  2. We then use the requests.get() function to load the API endpoint from the Bored API and assign it to our variable response
  3. We then use the .json() method, which serialized the returned string into a Python dictionary by parsing through the returned JSON data

Now that we have our JSON loaded from an API with Python, let’s take a look at how we can print it out in a prettier format:

# Pretty printing JSON Returned from an API
import requests
import json

response = requests.get("https://www.boredapi.com/api/activity")
json_response = response.json()
pretty_response = json.dumps(json_response, indent=4)

# You could also write:
pretty_response = json.dumps(response.json(), indent=4)

print(pretty_response)

# Returns:
# {
#     "activity": "Have a football scrimmage with some friends",
#     "type": "social",
#     "participants": 8,
#     "price": 0,
#     "link": "",
#     "key": "1638604",
#     "accessibility": 0.2
# }

Sorting Keys When Pretty Printing a JSON File in Python

When working with large JSON files, it can be very helpful to sort the keys in alphabetical order in order to understand the file better. We could use the sort_keys= parameter to ensure that our keys are sorted alphabetically.

Let’s take a look at how to sort our JSON keys in a pretty printed object:

import requests
import json

response = requests.get("https://www.boredapi.com/api/activity")
pretty_response = json.dumps(response.json(), indent=4, sort_keys=True)
print(pretty_response)

# Returns:
# {
#     "accessibility": 0.1,
#     "activity": "Go swimming with a friend",
#     "key": "1505028",
#     "link": "",
#     "participants": 2,
#     "price": 0.1,
#     "type": "social"
# }

In the code block above, we serialized an API response using the requests library. This allowed us to then dump the object to a string using the json.dumps() function. In this function, we specified that we wanted to indent the values using four spaces and that we wanted the keys sorted alphabetically.

Now that you have a strong understanding of how to pretty print a JSON file, let’s take a look at how to save these pretty printed objects to a file.

How to Pretty Print a JSON File From the Command Line

When you’re working in the Terminal, it can be helpful to pretty print a JSON file directly in the terminal. Python makes doing this quite easy! The json.tool module provides a simple and elegant command line interface to pretty-print JSON objects.

When you’re in your terminal, you can simply call the following command:

# Pretty Printing a JSON File from the Command Line
(base) nik % python3 -m json.tool sample.json
{
    "activity": "Plan a trip to another country",
    "type": "recreational",
    "participants": 1,
    "price": 0,
    "link": "",
    "key": "5554727",
    "accessibility": 0
}

The important part to run here is python3 -m json.tool sample.json where sample.json is the path to your JSON file. This will pretty print the JSON file directly in your terminal!

How to Save a Pretty Printed JSON to a File with Python

Now that you know how to use Python to pretty print a JSON file and a response from a web API, let’s take a look at how you can save the formatted version of the JSON object to a file. This can be helpful when you’re working with large objects, since reading the output in your code editor terminal may be harder than necessary.

In order to accomplish this, we’ll again use a context manager. This time, however, instead of using it to manage reading a file, we’ll use it to write a file. Because of this, we’ll change the mode= to 'w' for write.

Let’s get started!

# Saving a Pretty Printed JSON Object to a File
import requests
import json

response = requests.get("https://www.boredapi.com/api/activity")
save_filepath = 'pretty.json'

with open(file=save_filepath, mode='w') as output_file:
    json.dump(response.json(), output_file, indent=4)

Let’s see what we’ve done here:

  1. We created our response object
  2. We created a save_filepath variable to where we want to save our file to. In this case, the file will save to wherever the script is running.
  3. We use the with keyword to create a writeable file, where we then dump our object into, using the indent= keyword
  4. The context manager will handle closing the file once it’s done saving the file for us.

Using this approach, you’ve successfully saved a pretty printed JSON file using Python!

How to Pretty Print a JSON File in Python Using pprint

The pprint (“pretty print”) module comes built-in with Python 3 and allows you to easily pretty print different objects. Among these objects available to print nicer are JSON objects, that have been serialized to Python dictionaries!

Because the pprint library is built-in, you don’t need to install it. In order to use the library, we can import just the pprint function from the library.

# Using the pprint Library to Pretty Print a JSON File
import json
from pprint import pprint

with open('/Users/nikpi/Desktop/sample.json', 'r') as f:
    data = json.load(f)
    pprint(data)

# Returns:
# {'accessibility': 0,
#  'activity': 'Plan a trip to another country',
#  'key': '5554727',
#  'link': '',
#  'participants': 1,
#  'price': 0,
#  'type': 'recreational'}

In the code above, we loaded the JSON file as we had done before, using the json.load() function. We then passed the serialized object into the pprint() function, which allows us to print the file in a prettier, uncompressed way.

Conclusion

In this post, you learned how to pretty print a JSON object in Python. This can be a beneficial skill as you’re diving into analyzing JSON data or troubleshooting why something isn’t working as expected. You learned how to pretty print a JSON object from a JSON file, how to pretty print the JSON response from a web API in Python, as well as how to use Python to save a pretty printed JSON to a file.

To learn more about the JSON module, check out the official documentation here.

Additional Resources

To learn more about related topics, check out the tutorial below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

2 thoughts on “Pretty Print a JSON File in Python (6 Methods)”

  1. Pingback: Pandas: Iterate over a Pandas Dataframe Rows • datagy

  2. Pingback: Python Merge Dictionaries - Combine Dictionaries (7 Ways) • datagy

Leave a Reply

Your email address will not be published. Required fields are marked *