Dan's solution is just wrong, and Ismail's in incomplete.

  1. __str__() is not called, __repr__() is called.
  2. __repr__() should return a string, as pformat does.
  3. print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.

Here is an example

class S:
    def __repr__(self):
        from pprint import pformat
        return pformat(vars(self), indent=4, width=1)

a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c

print(a)

This prints

{   'b': 'bee',
    'c': {   'cats': [   'blacky',
                         'tiger'],
             'dogs': [   'rex',
                         'king']},
    'd': {   'more_c': {   'cats': [   'blacky',
                               'tiger'],
                  'dogs': [   'rex',
                              'king']}}}

Which is not perfect, but passable.

Answer from Charles Merriam on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pprint.html
pprint — Data pretty printer
Source code: Lib/pprint.py The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted struc...
Discussions

Pretty print JSON from URL
I've not done a lot in this space but something I have tried in the past with JSON's is to convert to a pandas DataFrame. I'm not sure if this is exactly what you are after, but the following stackoverflow post may help: https://stackoverflow.com/questions/21104592/json-to-pandas-dataframe More on reddit.com
🌐 r/learnpython
13
2
August 27, 2021
python - How to prettyprint a JSON file? - Stack Overflow
I get the following error message ... the JSON object must be str, not 'bytes'" 2018-01-23T08:41:42.08Z+00:00 ... "without requiring the JSON to be on your computer as a local file: " - the question explicitly asked about a file, though. While it could potentially be useful to others to show how to grab the data from an Internet source, that is a separate problem pertaining to a separate question. (If someone had asked how to download a JSON file and pretty-print it, that would ... More on stackoverflow.com
🌐 stackoverflow.com
python - Is there a built-in function to print all the current properties and values of an object? - Stack Overflow
So what I'm looking for here is something like PHP's print_r function. This is so I can debug my scripts by seeing what's the state of the object in question. More on stackoverflow.com
🌐 stackoverflow.com
New Protocol for Pretty Printing
Looks pretty cool to me. dataclasses have this kind of repr thing built in, but it would be nice to have this tool if i were doing something else, to build them on my own. that said, your code above requires putting in the defaults twice. i bet you could automate the work inside __rich_repr__ by using inspect.signature, something like this: from inspect import signature from rich.repr import rich_repr @rich_repr class Bird: def __init__(self, name, eats=None, fly=True, extinct=False): self.name = name self.eats = list(eats) if eats else [] self.fly = fly self.extinct = extinct def __rich_repr__(self): for name, param in signature(Bird).parameters.items(): if param.default == param.empty: yield name, getattr(self, name) else: yield name, getattr(self, name), param.default if __name__ == "__main__": print(Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"])) print(Bird("penguin", eats=["fish"], fly=False)) print(Bird("dodo", eats=["fruit"], fly=False, extinct=True)) More on reddit.com
🌐 r/Python
2
66
May 8, 2021
🌐
Real Python
realpython.com › python-pretty-print
Prettify Your Data Structures With Pretty Print in Python – Real Python
October 4, 2022 - It’s possible to create an instance of PrettyPrinter that has defaults you’ve defined. Once you have this new instance of your custom PrettyPrinter object, you can use it by calling the .pprint() method on the PrettyPrinter instance: ... >>> from pprint import PrettyPrinter >>> custom_printer = PrettyPrinter( ...
🌐
seenode blog
seenode.com › blog › how-to-use-python-pretty-print-pprint
How to Use Python Pretty Print (pprint) for Cleaner Python Output | seenode blog
May 19, 2025 - The key value prints based on their order insertion if it is set to False. Its default value is True. ... For example, if you want to work with JSON data from an API, or parsing log files, or debug Python objects with lots of levels, pprint should be your first choice that will save time. Firstly, you need to import the pprint module. ... You can use the pprint() method or instantiate your pprint object with PrettyPrinter().
🌐
Reddit
reddit.com › r/learnpython › pretty print json from url
r/learnpython on Reddit: Pretty print JSON from URL
August 27, 2021 -

Hello Everyone,

I've hit a frustrating wall and after much googling I took a deep breath and felt the best approach was to ask you all for advice.

I'm making a very simple script and need assistance with what tool I should use to move forward.

Step 1: Fetch the URL Step 2: Make the JSON pretty. Such as a top-down listing of Title and URL only.

import requests

#make the URL call
page = requests.get('http://gleamlist.com:5000/api')
#verify the page has content - just for testing.
print(page.content)

I've tried using the json module but confuse myself and I've thought maybe BS4 would help but also confuse myself. I believe JSON is basically a dictionary and I want to parse out the info. Could anyone assist me with some tips or a specific topic to research and implement please?

🌐
Rich
rich.readthedocs.io › en › latest › pretty.html
Pretty Printing — Rich 14.1.0 documentation
Run the following command to see an example of pretty printed output: python -m rich.pretty · Note how the output will change to fit within the terminal width. The pprint() method offers a few more arguments you can use to tweak how objects are pretty printed.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - Learn how to pretty print JSON in Python using built-in tools like json.dumps() and pprint to improve readability and debug structured data efficiently.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › pprint-data-pretty-printer-python
pprint : Data pretty printer in Python - GeeksforGeeks
The pprint module (pretty print) is a built-in utility that formats complex data structures like dictionaries, lists, or JSON in a readable way with proper indentation and line breaks.
Published   January 9, 2026
🌐
W3Schools
w3schools.com › python › ref_module_pprint.asp
Python pprint Module
Pretty-print nested data in a readable ... "editor"]}]} pprint(data) Try it Yourself » · The pprint module formats Python objects in a way that's easier for humans to read....
🌐
TestDriven.io
testdriven.io › tips › cce7ddc9-81be-4851-8287-199ba65378a5
Tips and Tricks - Python pprint – pretty-print data structures | TestDriven.io
You can use pprint.pprint to print a formatted representation of an object. ... import json import pprint from urllib.request import urlopen with urlopen("https://pypi.org/pypi/flask/json") as resp: project_info = json.load(resp)["info"] ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Pretty-print in Python: pprint | note.nkmk.me
May 17, 2023 - In Python, you can pretty-print objects such as lists (list) and dictionaries (dict) with the pprint module. pprint — Data pretty printer — Python 3.11.3 documentation Basic usage of pprint Specify ...
Top answer
1 of 15
3096

Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by:

>>> import json
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
    "foo",
    {
        "bar": [
            "baz",
            null,
            1.0,
            2
        ]
    }
]

To parse a file, use json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)
2 of 15
500

You can do this on the command line:

python3 -m json.tool some.json

(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).

Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.

You can also use jq:

jq . some.json

and you get colors as a bonus (and way easier extendability).

Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.

🌐
Analytics Vidhya
analyticsvidhya.com › home › how to use pprint in python? [explained with examples]
How to Use PPrint in Python? [Explained with Examples]
October 19, 2024 - A. Pprint (pretty print) is a Python module used for formatting complex data structures more readably and organized, especially when printing them to the console or writing to a file.
🌐
Python Module of the Week
pymotw.com › 2 › pprint › index.html
pprint – Pretty-print data structures - Python Module of the Week
It formats your object and writes it to the data stream passed as argument (or sys.stdout by default). from pprint import pprint from pprint_data import data print 'PRINT:' print data print print 'PPRINT:' pprint(data) $ python pprint_pprint.py PRINT: [(0, {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', 'g': 'G', 'f': 'F', 'h': 'H'}), (1, {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', 'g': 'G', 'f': 'F', 'h': 'H'}), (2, {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', 'g': 'G', 'f': 'F', 'h': 'H'})] PPRINT: [(0, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'}), (1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'}), (2, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'})]
🌐
Python Engineer
python-engineer.com › posts › pprint-python
How to use pprint in Python? - Python Engineer
May 17, 2022 - [{'application': ['Data Science', ... and above. Returns True if the object passed is readable by pprint, if an object is readable it can be pretty printed....
🌐
Reddit
reddit.com › r/python › new protocol for pretty printing
r/Python on Reddit: New Protocol for Pretty Printing
May 8, 2021 -

I've recently documented a protocol in Rich to add pretty printing to arbitrary objects.

The problem was that containers like dicts, lists, sets etc could be formatted over multiple lines, but custom classes are limited to a string that can be generated from __repr__. The new protocol in Rich adds a __rich_repr__ method which allows an object to declare how it should be pretty printed.

Looking for feedback. Here are the docs.

Here's an example of a __rich_repr__ method.

And here's what it looks like when you pretty print a Bird instance:

🌐
Python.org
discuss.python.org › ideas
Format specifier for pretty printing - Ideas - Discussions on Python.org
February 4, 2025 - Since python has format specifiers, I was wondering whether these could be use to add pretty printing functionality to any object. The pprint module could then make use of this, by delegating the formatting to the objects themselves with a fallback to the current implementation (eg the ...
🌐
Jython
jython.org › jython-old-sites › docs › library › pprint.html
8.18. pprint — Data pretty printer — Jython v2.5.2 documentation
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
🌐
Reddit
reddit.com › r/learnpython › printing a class object?
r/learnpython on Reddit: Printing a class object?
January 22, 2023 -

I'm trying to use the pokebase wrapper just to explore and I'm really struggling with it.

I just want to print all the moves a pokemon has but they show up as locations in memory instead of the actual values. I'm not sure how to get the data out of this.

import pokebase as pb

pokemon = pb.pokemon(1)
print(pokemon.moves)

Example of results:

[<pokebase.interface.APIMetadata object at 0x000001E774593C70>, <pokebase.interface.APIMetadata object at 0x000001E774543940>, <pokebase.interface.APIMetadata object at 0x000001E774593B20>]