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))
return

pj(thing_containing_raw_json_here)

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 = requests.post(todoistURL+"/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:
Please share if you found this useful!
Facebooktwittergoogle_plusredditlinkedin

2 thoughts on “Pretty print JSON in Python (snippet)

  1. 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!

    Can’t
    json.dumps(json.loads(str.content), indent=4)
    become
    json.dumps(str,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.