Python pretty print JSON | Example code

Pretty printing means having proper line breaks, indentation, white space, and overall structure. Use json.dumps() to pretty print out the JSON in a more structured format in Python.

Use the Indent keyword while dumping the data decides to what level spaces the user wants.

json.dumps(json_object, indent = 1)

Example Python pretty print JSON

Simple example code.

import json

data = '[{"Emp ID":101,"Name":"John","Designation":"Engineer"},' \
       '{"Emp ID":102,"Name":"Tim","Designation":"Marketing"}]'

res = json.loads(data)

# Indent = 3
print(json.dumps(res, indent=3))

Output:

Python pretty print JSON

How to Pretty Print JSON From an API in Python?

Answer: Import required libraries and use the requests.get() method to load the API endpoint from the Bored API and assign it to our variable response

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)

print(pretty_response)

Output:

{
“activity”: “Do a jigsaw puzzle”,
“type”: “recreational”,
“participants”: 1,
“price”: 0.1,
“link”: “https://en.wikipedia.org/wiki/Jigsaw_puzzle”,
“key”: “8550768”,
“accessibility”: 1
}

Do comment if you have any doubts and suggestions on this Python print topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.