Python Pretty print JSON – A Complete Guide

Python Pretty Print JSON

In this article, we’ll learn how to print a JSON file. You may get confused by the title “Python Pretty Print JSON”. Let’s understand that as well. Before getting into it, we first need to understand a JSON file.

Understanding the JSON file format

JSON is a syntax or format to store data and transfer or exchange over the network in textual forms. It is easy to read and write by machines as well as humans also. A lot of APIs and Databases use this format for the same. JSON stands for JavaScript Object Notation. Its filename extension for written programming code is .json . Let us read some key features of our JSON files.

  • JSON provides an easy-to-use method to work on.
  • It depicts a minimized form of data using very lesser space that results in it being quite faster.
  • It is open-source and free to use.
  • It gives clean, compatible, and easy-to-read results.
  • JSON is not having any dependencies that help him to run independently.
  • The syntax for writing data into the JSON file is exactly the same as Python Dictionary.

Let us look into the JSON file below.

{
  "name": "mine",
  "version": "1.0.0",
  "description": "hey ",
  "main": "2.js",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.12.9",
    "nodemon": "^2.0.7",
    "pug": "^3.0.2"
  }}

In the above example, you can see that A JSON file most probably looks like a python dictionary containing some keys (name, version, description, main, dependencies) and values (mine, 1.0.0, hey, 2.js, {“express”: “^4.17.1”, “mongoose”: “^5.12.9″,”nodemon”: “^2.0.7”, “pug”: “^3.0.2” } ).

It is structured as well. We can see the same if we opened it using ms_doc or in notepad. But using the python print function it will print as unstructured as follows. We need to print the same in a structured format that is to be beautiful or in a prettier way.

{{
  "name": "mine", "version": "1.0.0","description": "hey ","main": "2.js","dependencies": {"express": "^4.17.1","mongoose": "^5.12.9","nodemon": "^2.0.7","pug": "^3.0.2"
  }}

Reading JSON file

Our first step will be to read the JSON file. Let us have a look at our Code snippet as well.

import json
with open(file="/content/package.json", mode='r') as our_file:
    output = json.load(our_file)
    print(output)

In the above code snippet, We use

  • The with keyword to open our JSON file.
  • The mode='r' parameter to open the file in the read-only mode.
  • The json.load() method loads our file into an object file named output.

After printing the same we get our JSON file printed as below.

{'name': 'mine', 'version': '1.0.0', 'description': 'hey ', 'main': '2.js', 'dependencies': {'express': '^4.17.1', 'mongoose': '^5.12.9', 'nodemon': '^2.0.7', 'pug': '^3.0.2'}, 'devDependencies': {}, 'scripts': {'test': 'echo "Error: no test specified" && exit 1'}, 'author': 'brand', 'license': 'ISC'}

You can see that by normal printing we should get the output that is not formatted, beautiful, or structured as well. We want it to be printed beautifully, and well structured. We used the keyword Pretty for the same only. (Pretty means beautiful. We need o print our JSON file in a beautiful way.)

We can get our expected result by some special methods or using some special libraries as well. Let’s have it.

Printing JSON using json.dumps() method

json.dump( object_name, indent = "your value")

The above depicts the syntax for the json.dumps() method. We need to pass the object name in which the json file was been loaded and to pass the indent value which specifies number of spaces we want to use to indent our JSON. We just need to add this single line only to get our Prettier JSON file printed. Let’s have quick look below.

with open(file="/content/package.json", mode='r') as our_file:
    output = json.load(our_file)
    pretty_output = json.dumps(output, indent=4)
    print(pretty_output)

We could get our printed JSON file as follows.

{
    "name": "mine",
    "version": "1.0.0",
    "description": "hey ",
    "main": "2.js",
    "dependencies": {
        "express": "^4.17.1",
        "mongoose": "^5.12.9",
        "nodemon": "^2.0.7",
        "pug": "^3.0.2"
    },
    "devDependencies": {},
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "brand",
    "license": "ISC"
}

Priting JSON using the pprint Library

The pprint module provides the pprint() method in Python that is used to print data in a readable and pretty way. It’s a part of the standard library those are highly recommended for code debugging purpose along with API requests and databases. Let us see how to use the same in our code snippet.

import json
from pprint import pprint

with open("/content/package.json", 'r') as our_file:
    output = json.load(our_file)
    pprint(output)

In the above code snippet, we have loaded our JSON file as we had done before, using the json.load() method and We then passed the serialized object that is our_file into the pprint() method, that allows us to print a structured and pretty output as well.

{'author': 'brand',
 'dependencies': {'express': '^4.17.1',
                  'mongoose': '^5.12.9',
                  'nodemon': '^2.0.7',
                  'pug': '^3.0.2'},
 'description': 'hey ',
 'devDependencies': {},
 'license': 'ISC',
 'main': '2.js',
 'name': 'mine',
 'scripts': {'test': 'echo "Error: no test specified" && exit 1'},
 'version': '1.0.0'}

Summary

Today, We covered Pretty print using python. We learned how to print a JSON file in a prettier way. We used two methods as well and got the same. Hope You must have enjoyed it as well. We must visit again with some more interesting topics.