Python: Pretty Print JSON (3 Different Ways!)

Python Pretty Print JSON Cover Image

In this tutorial, you’ll learn how to use Python to pretty print JSON. You’ll learn how to pretty print a JSON object, how to pretty a JSON file, and how to save a pretty printed JSON to a file.

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.

The Quick Answer: Use json.dumps

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 machine 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 grant 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, lets 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:

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}

By using the with keyword, Python manages some of the resourcing of opening the file for us. We can then, as shown above, use the alias we assign, read_file, in the indented portion of our code.

When we print out the file, we can see that it’s printed out as the minimized, flat version of JSON code. 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)

When we run the code above, we now get a nicely formatted string that looks like this:

{
    "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 imported the json library
  2. 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.
  3. We then use a context manager to read our file (this is indicated by mode='r'
  4. We load our JSON object using the json.load() method, which we then dump into a string using the .dumps() method
  5. Within that method, we specify how much we want our pretty-printed JSON file to be indented.
  6. Finally, we print the file and it’s looking much, much prettier!

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

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. 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 get started!

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 our required libraries. While we’re not yet using json, it’s helpful to already have it imported.
  2. We then use the requests.get() method to load the API endpoint from the Bored API and assign it to our variable response
  3. Finally, we print the .json() version of our response object, which really just means that we resolve the response itself to a json version

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:

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)

This returns the following formatted JSON string:

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

Similarly, we could use the sort_keys= parameter to ensure that our keys are sorted alphabetically. This can be particularly helpful when dealing with large JSON objects.

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)

This returns the following:

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

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 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!

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 imported our libraries
  2. We created our response object and created a save_filepath variable to where we want to save our file to
  3. We use the with keyword to create a writeable file, where we then dump our object into, using the indent= keyword

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

Conclusion

In this post, you learned how to pretty print a JSON object in Python. This can be an immensely helpful 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.