Pretty print JSON in Python (snippet)

JSON logoThe below depends on the json Python module to ‘pretty print’ JSON output in Python. I found this useful when trying to write my script to remove unused Todoist labels.

import json

# This function saves time printing JSON nicely
def pj(str):
print(json.dumps(json.loads(str.content), indent=4))


Note that in my case this was contingent on having used the requests module in the following fashion to already make sure the format is a bit jsonified, if I understand the .json at the end, which is not 100% guaranteed.

r ="/login", params=loginParams).json()

There are numerous other ways to get JSON from an API or whatever than just using requests (I think people also use urllib?), but this is the route I took.

photo by:

By Tom Bush

Hi, my name is Tom Bush and this is my site. Welcome :)

2 replies on “Pretty print JSON in Python (snippet)”

Nice article :), but some thoughts:

– Generally bad practice to override built in language names (looking at you str)
– The var name is called str but isn’t a string as I read it, otherwise you wouldn’t be calling str.content. Stand to be correct though!

json.dumps(json.loads(str.content), indent=4)

Leave a Reply

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

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