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)
Answer from Blender on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
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.
🌐
Educative
educative.io › answers › how-to-pretty-print-json-objects-in-python
How to pretty print JSON objects in Python
Line 4: We create a jsonData variable with a hard-coded JSON array. Line 8: We use the loads() function from the json module. The function helps to convert our jsonData string to a Python object and store it in jsonObject.
🌐
ReqBin
reqbin.com › code › python › 0l6wsqxp › python-pretty-print-json-example
How do I pretty print JSON in Python?
To pretty print a JSON string in Python, you can use the json.dumps(indent) method of the built-in package named json. First, you need to use the json.loads() method to convert the JSON string into a Python object.
Top answer
1 of 15
3108

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
502

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.

🌐
GeeksforGeeks
geeksforgeeks.org › json-pretty-print-using-python
JSON Pretty Print using Python - GeeksforGeeks
August 7, 2022 - First, use json.loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json.dumps() method is used. Below are examples and steps to better understand these cases.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pretty-print-json
Python - Pretty Print JSON - GeeksforGeeks
July 23, 2025 - To validate and pretty-print JSON objects from the command line, Python offers the json.tool package.
Top answer
1 of 4
5

Here is a way to do it with as least amount of modifications as possible:

import json
from json import JSONEncoder
import re

class MarkedList:
    _list = None
    def __init__(self, l):
        self._list = l

z = {    
    "rows_parsed": [
        MarkedList([
          "a",
          "b",
          "c",
          "d"
        ]),
        MarkedList([
          "e",
          "f",
          "g",
          "i"
        ]),
    ]
}

class CustomJSONEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, MarkedList):
            return "##<{}>##".format(o._list)

b = json.dumps(z, indent=2, separators=(',', ':'), cls=CustomJSONEncoder)
b = b.replace('"##<', "").replace('>##"', "")

print(b)

Basically the lists that you want formatted in that way you make instance of MarkedList and they get parsed as strings with hopefully unique enough sequence that is later stripped from the output of dumps. This is done to eliminate the quotes that are put around a json string.

Another much more efficient way to do it, but a much more ugly one is to monkey patch json.encoder._make_iterencode._iterencode with something like:

def _iterencode(o, _current_indent_level):
    if isinstance(o, str):
        yield _encoder(o)
    elif o is None:
        yield 'null'
    elif o is True:
        yield 'true'
    elif o is False:
        yield 'false'
    elif isinstance(o, int):
        # see comment for int/float in _make_iterencode
        yield _intstr(o)
    elif isinstance(o, float):
        # see comment for int/float in _make_iterencode
        yield _floatstr(o)
    elif isinstance(o, MarkedList):
        yield _my_custom_parsing(o)
    elif isinstance(o, (list, tuple)):
        yield from _iterencode_list(o, _current_indent_level)
    elif isinstance(o, dict):
        yield from _iterencode_dict(o, _current_indent_level)
    else:
        if markers is not None:
            markerid = id(o)
            if markerid in markers:
                raise ValueError("Circular reference detected")
            markers[markerid] = o
        o = _default(o)
        yield from _iterencode(o, _current_indent_level)
        if markers is not None:
            del markers[markerid]
2 of 4
1

I don't see how you could do it in the json.dumps. After a bit of searching I came across a few options: One option would be to do some post-processing with a custom function:

def fix_json_indent(text, indent=3):
            space_indent = indent * 4
    initial = " " * space_indent
    json_output = []
    current_level_elems = []
    all_entries_at_level = None  # holder for consecutive entries at exact space_indent level
    for line in text.splitlines():
        if line.startswith(initial):
            if line[space_indent] == " ":
                # line indented further than the level
                if all_entries_at_level:
                    current_level_elems.append(all_entries_at_level)
                    all_entries_at_level = None
                item = line.strip()
                current_level_elems.append(item)
                if item.endswith(","):
                    current_level_elems.append(" ")
            elif current_level_elems:
                # line on the same space_indent level
                # no more sublevel_entries 
                current_level_elems.append(line.strip())
                json_output.append("".join(current_level_elems))
                current_level_elems = []
            else:
                # line at the exact space_indent level but no items indented further
                if all_entries_at_level:
                    # last pending item was not the start of a new sublevel_entries.
                    json_output.append(all_entries_at_level)
                all_entries_at_level = line.rstrip()
        else:
            if all_entries_at_level:
                json_output.append(all_entries_at_level)
                all_entries_at_level = None
            if current_level_elems:
                json_output.append("".join(current_level_elems))
            json_output.append(line)
    return "\n".join(json_output)

Another possibility is a regex but it is quite ugly and depends on the structure of the code you posted:

def fix_json_indent(text):
    import re
    return  re.sub('{"', '{\n"', re.sub('\[\[', '[\n[', re.sub('\]\]', ']\n]', re.sub('}', '\n}', text))))
🌐
freeCodeCamp
freecodecamp.org › news › how-to-pretty-print-json-in-python
How to Pretty Print JSON in Python
April 14, 2023 - This module provides a dumps() function that can serialize Python objects into a JSON formatted string. By default, this function produces a JSON string without any formatting, but we can use the indent parameter to specify the number of spaces to use for indentation. Here's an example of how to pretty print JSON in Python:
Find elsewhere
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.8 documentation
The json module can be invoked as a script via python -m json to validate and pretty-print JSON objects.
🌐
datagy
datagy.io › home › python posts › pretty print a json file in python (6 methods)
Pretty Print a JSON File in Python (6 Methods) • datagy
August 31, 2022 - When you look at a JSON file, you’ll ... is to a Python dictionary. In fact, this is true for many other languages, making JSON a great data interchange format. JSON will contain a key and a value for each pair, separated by commas. A value can also be a list (or array) of items, or another dictionary-like object. Let’s take a look at what we mean by pretty printing JSON in ...
🌐
PYnative
pynative.com › home › python › json › python prettyprint json data
Python PrettyPrint JSON Data
May 14, 2021 - If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. For example, when we specify indent=4, Python uses four spaces for indentation.
🌐
Python
docs.python.org › 3 › library › pprint.html
pprint — Data pretty printer
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › pretty-print-json-in-python
Pretty Print JSON in Python - GeeksforGeeks
April 28, 2025 - Example 2: Let's suppose we want to pretty-print the data from the JSON file. JSON File: ... import json # Opening JSON file f = open('myfile.json',) # returns JSON object as # a dictionary data = json.load(f) print(json.dumps(data, indent = 1) # Closing file f.close() ... { "emp1": { "name": "Lisa", "designation": "programmer", "age": "34", "salary": "54000" }, "emp2": { "name": "Elis", "designation": "Trainee", "age": "24", "salary": "40000" } } ... Python Tutorial – Python is one of the most popular programming languages.
Top answer
1 of 1
1
Explain Python Pretty Print JSONJSON (JavaScript Object Notation) is a widely used data format for data interchange. It's human-readable and machine-friendly, making it a popular choice for configuration files, APIs, and data storage. Sometimes, when working with JSON data in Python, you might encounter large or complex JSON structures that are challenging to read. That's where Python's "pretty print" functionality comes into play.Pretty printing is the process of formatting JSON data to make it more legible and visually appealing to humans. Python provides a built-in module called `json` that includes a `dumps()` method. Using this method with specific parameters lets you easily print JSON data.In this article, we'll explore using Python's `json.dumps()` method to pretty print JSON data.PrerequisitesBefore we dive into pretty printing JSON in Python, ensure you have Python installed on your system. You can download it from the official Python website: https://www.python.org/downloads/What is JSON?JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It's often used to transmit data between a server and a web application or between different parts of an application.JSON data is represented as a collection of key-value pairs, similar to Python dictionaries. Here's a simple example:json{    "name": "John Doe",    "age": 30,    "city": "New York"}In Python, JSON data is typically converted to dictionaries or lists using the `json` module, making it easy to work with.Using `json.dumps()` for Pretty PrintingPython's `json.dumps()` function converts a Python object into a JSON formatted string. By default, the JSON output is compact and not very human-readable. You can use the `indent` parameter to make it more readable.Here's the basic syntax of `json.dumps()` with the `indent` parameter:import jsonpretty_json = json.dumps(your_data, indent=4) `your_data`: This is the Python object (e.g., dictionary or list) that you want to convert to JSON. `indent=4`: This parameter specifies the number of spaces to use for indentation in the resulting JSON string. In this case, we use 4 spaces to make it nicely formatted.Example: Pretty Printing JSONLet's see an example of pretty printing JSON in Python:import json# Sample JSON datadata = {    "name": "John Doe",    "age": 30,    "city": "New York",    "skills": }# Pretty print the JSON datapretty_json = json.dumps(data, indent=4)# Print the pretty JSONprint(pretty_json)When you run this code, it will produce the following nicely formatted JSON output:json{    "name": "John Doe",    "age": 30,    "city": "New York",    "skills": }As you can see, the JSON data is now structured with proper indentation, making it much easier to read and understand.Use Cases for Pretty PrintingPretty printing JSON is particularly helpful in scenarios where: Debugging: When you're working with JSON data and need to debug or inspect it, pretty printing makes it more human-readable and helps you identify issues more easily. Logging: If you're logging JSON data in your application, pretty print formatting can make your log files more organized and user-friendly. Configuration Files: Pretty printing is beneficial when dealing with configuration files in JSON format. It ensures that configuration settings are neatly organized. API Development: When building or consuming JSON APIs for data exchange, pretty printing can assist in documenting and testing the API endpoints.ConclusionPython's `json.dumps()` method with the `indent` parameter is a valuable tool for pretty much printing JSON data. It allows you to format JSON in a human-readable way, making it easier to work with, debug, and understand. Whether you're developing web applications, working with configuration files, or dealing with API data, pretty printing JSON can significantly improve your workflow and code readability.
🌐
MLJAR
mljar.com › docs › python-pretty-print-json
Pretty print JSON in Python
Pretty print JSON or dict objects in Python. It is much easier to understand JSON objects that has nice indentation.
🌐
Python Guides
pythonguides.com › python-pretty-print-json
How to Pretty Print JSON in Python
August 12, 2025 - The sort_keys=True parameter is particularly helpful when I need consistent output for version control or comparing JSON files. Python’s pprint module is another excellent option for pretty printing JSON data.
🌐
DEV Community
dev.to › pineapple_26 › json-pretty-print-using-python-with-examples-12ha
JSON Pretty Print Using Python - With Examples - DEV Community
November 20, 2025 - The easiest way to pretty print JSON in Python is using json.dumps() with the indent parameter.
🌐
Medium
medium.com › @blogshub4 › how-to-pretty-print-a-json-string-in-python-98a85f99ecb4
How to Pretty Print a JSON String in Python | by Blogshub | Medium
December 22, 2024 - Pretty-printing JSON strings in Python is simple with the help of the built-in json module. By using the json.dumps() method with an…
🌐
PyTutorial
pytutorial.com › python-pretty-print-json-guide
PyTutorial | Python Pretty Print JSON Guide
November 5, 2024 - The simplest way to pretty print JSON is using the json.dumps() method with the indent parameter. This is part of Python's built-in json module.