How to Pretty Print JSON in Python?

By Hardik Savani October 30, 2023 Category : Python

Hey Dev,

In this article, we will cover pretty print json in python. you will learn pretty print python json. We will look at an example of how to pretty print json in python. If you have a question about how to pretty print json response in python then I will give a simple example with a solution. Alright, let us dive into the steps.

In you want to display json in proper format from string in python then i will give you two examples to do pretty print json in python language. first we will use json.dumps() and second one will use pprint.pprint() function. So, without further ado, let's see simple examples: You can use these examples with python3 (Python 3) version.

Example 1: Python Pretty Print JSON using json.dumps()

main.py

import json

# Create New Json
myJson = [{"id": 1,"name": "Hardik"}, {"id": 2,"name": "Vimal"}, {"id": 3,"name": "Harshad"}]

# Display JSON with Prettyprint
print(json.dumps(myJson, sort_keys=False, indent=4))

Output:

[
    {
        "id": 1,
        "name": "Hardik"
    },
    {
        "id": 2,
        "name": "Vimal"
    },
    {
        "id": 3,
        "name": "Harshad"
    }
]

Example 2: Python Pretty Print JSON using pprint.pprint()

main.py

import pprint

# Create New Json
myJson = [{"id": 1,"name": "Hardik"}, {"id": 2,"name": "Vimal"}, {"id": 3,"name": "Harshad"}]

# Display JSON with Prettyprint
pprint.pprint(myJson)

Output:

[{'id': 1, 'name': 'Hardik'},
 {'id': 2, 'name': 'Vimal'},
 {'id': 3, 'name': 'Harshad'}]

I hope it can help you...

Tags :
Shares