Skip to content

Python pretty print JSON | Example code

  • by

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.

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

json.dumps(json_object, indent = 1)

Example Python pretty prints 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 or suggestions on this Python print topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

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