The json.dumps() function in Python formats a Python object into a JSON-formatted string, and the indent parameter controls the indentation level for readability.

json.dumps() with indent:

  • indent=4 adds four spaces per nesting level, producing a standard pretty-printed format.

  • indent=2 uses two spaces per level, ideal for more compact readability.

  • indent=None (default) produces the most compact output with no extra whitespace.

  • indent=0 or negative values insert only newlines, no spaces.

Example:

import json
data = {"name": "Alice", "age": 30, "hobbies": ["reading", "chess"]}
print(json.dumps(data, indent=4))

Output:

{
    "name": "Alice",
    "age": 30,
    "hobbies": [
        "reading",
        "chess"
    ]
}

Key Options:

  • sort_keys=True: Sorts dictionary keys alphabetically.

  • separators=(',', ': '): Customizes spacing around commas and colons (e.g., (',', ': ') for readable output).

  • ensure_ascii=False: Allows non-ASCII characters (e.g., emojis) to be preserved.

Use json.dumps() for string output; use json.dump() to write directly to a file with indent.

Python 2.7

there is a workaround that can be implemented using regular expressions :

import re
dump = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
#Replaces spaces with tab
new_data = re.sub('\n +', lambda match: '\n' + '\t' * (len(match.group().strip('\n')) / 3), dump)
json.dump(new_data, open('dev_integrated.json', 'w')

Python 3.2+

From the Docs :

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

Hence the TAB-indentation can be implemented as follows:

json.dump(jString, open('dev_integrated.json', 'w'), sort_keys=True, indent='\t', separators=(',', ': '))
Answer from Stack on Stack Overflow
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
2 weeks ago - Disable escaping of non-ascii characters, see json.dumps() for more information. Added in version 3.9. --json-lines¶ · Parse every input line as separate JSON object. Added in version 3.8. --indent, --tab, --no-indent, --compact¶ · Mutually exclusive options for whitespace control.
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-json › writing-json-files › writing-to-json-file › jsondumps-options-the-indent
How to Read and Write JSON Files in Python | Learn Python | Vertabelo Academy
A positive integer indent indent represents the number of spaces per level that should be used to indent the content. An indent level of 0 or negative will only insert newlines. None (the default) selects the most compact representation.
Discussions

python - How to prettyprint a JSON file? - Stack Overflow
For simple pretty-printing this also works without explicit parsing: print json.dumps(your_json_string, indent=4) 2014-08-04T14:07:01.31Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
Will json.dump() get the indent argument?
I am wondering if adding "indent" argument to json.dump() may be in any plan. My use case is to write json strings to the dev board so it can be later opened say in Thonny and easily modi... More on github.com
🌐 github.com
1
1
November 24, 2024
JSON dumps indent tab
use simplejson instead More on reddit.com
🌐 r/learnpython
2
3
October 12, 2016
removing new line inside square brackets in json file
It parses it on to one line for me. Post an example code to recreate the issue. More on reddit.com
🌐 r/learnpython
5
11
November 5, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-dumps-in-python
json.dumps() in Python - GeeksforGeeks
Example 2: This example formats JSON output to make it more readable using indentation. ... The JSON string becomes easy to read. Example 3: This example sorts dictionary keys alphabetically before converting them to JSON. ... Useful for consistent JSON output. Example 4: This example shows how json.dumps() converts a Python list into a JSON-formatted string, which is commonly used when sending list data through APIs.
Published   January 13, 2026
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.

🌐
GitHub
github.com › orgs › micropython › discussions › 16296
Will json.dump() get the indent argument? · micropython · Discussion #16296
November 24, 2024 - If you know something about the json structure, you may be able to save memory , and add indentation at the same time. I have used that for a few years already in MicroPython-stubber - createstubs.py. ... # write 'header' # write json by node to reduce memory requirements with open(self._json_name, "w") as f: f.write("{") f.write(dumps({"firmware": self.info})[1:-1]) f.write(",\n") f.write(dumps({"stubber": {"version": __version__}, "stubtype": "firmware"})[1:-1]) f.write(",\n") f.write('"modules" :[\n') # Write data array with open(self._json_name, "a") as f: if not self._json_first: f.write(",\n") else: self._json_first = False # Add indentation to the line below indent = 4 line = '{{{}"module": "{}", "file": "{}"}}'.format(" "*indent, module_name, stub_file.replace("\\", "/")) f.write(line) # Write 'trailer' with open(self._json_name, "a") as f: f.write("\n]}")
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - The best and easiest way to indent JSON output in Python is by using the the indent parameter in the json.dumps() function.
🌐
Reddit
reddit.com › r/learnpython › json dumps indent tab
r/learnpython on Reddit: JSON dumps indent tab
October 12, 2016 -

We use Python 2.7 and I want to change the indention of JSON.dumps() to TABS instead of SPACES. When you do indent=8, it will insert 8 spaces, but I want to insert 2 tabs. I have read that this is possible in Python 3.3 by doing indent="\t\t" but we use Python 2.7.

🌐
Pradet
quentin.pradet.me › blog › indenting-json-in-python.html
Indenting JSON in Python
def output_unescaped_json(value, *, indent=0): out = '' next_indent = indent + 2 if isinstance(value, int): out += str(value) elif isinstance(value, list): # opening [ and indentation until first item out += '[\n' + ' ' * next_indent # each item separated by commas and indentation out_items = [ output_unescaped_json(item, indent=next_indent) for item in value ] sep = ',\n' + ' ' * next_indent out += sep.join(out_items) # indentation between the last item and ] out += '\n' + ' ' * indent + ']' else: assert False, type(value) return out
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write JSON data to a file in Python | Sentry
import json data = {"firstname": "John", "lastname": "Doe", "age": 35} with open("data.json", "w") as f: json.dump(data, f, indent=4)
🌐
JSON for Modern C++
json.nlohmann.me › api › basic_json › dump
dump - JSON for Modern C++
string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler = error_handler_t::strict) const; Serialization function for JSON values.
🌐
Reddit
reddit.com › r/learnpython › formatting json output in python
r/learnpython on Reddit: formatting json output in Python
May 12, 2022 -

Hi,

I would like to read json into Python code, and then output processed json. In order to get started with this, I have written very basic Python, and am attempting to read in very basic json I found online.

The input json is:

{
    "firstName": "John",
    "lastName": "Doe",
    "hobbies": ["biking", "coding", "rapping"],
    "age": 35,
    "children": [
        {
            "firstName": "hector",
            "age": 6
        },
        {
            "firstName": "cassandra",
            "age": 8
        }
    ]
}

The code is:

import json

if __name__ == '__main__':
    
    print( "start" )

    # read and load input json
    json_input_filename = "input.json"
    json_input = open( json_input_filename )

    json_input_dict = json.load( json_input )

    # write output json
    json_output_filename = "output.json"
    with open( json_output_filename, 'w' ) as json_output:
        json.dump( json_string, json_output )
  

    print( f"end" )

and the output is:

"{\"firstName\": \"John\", \"lastName\": \"Doe\", \"hobbies\": [\"biking\", \"coding\", \"rapping\"], \"age\": 35, \"children\": [{\"firstName\": \"hector\", \"age\": 6}, {\"firstName\": \"cassandra\", \"age\": 8}]}"

What can I do in order to preserve something resembling the original formatting? I'm going to load this output into some other code in order to process it further.

Thank you very much

🌐
freeCodeCamp
freecodecamp.org › news › how-to-pretty-print-json-in-python
How to Pretty Print JSON in Python
April 14, 2023 - import json # Sample JSON data data = { "name": "John", "age": 30, "city": "New York" } # Convert the data to a JSON formatted string with 4 spaces of indentation json_str = json.dumps(data, indent=4) # Print the pretty-printed JSON string ...
🌐
Simon Willison
til.simonwillison.net › json › streaming-indented-json-array
Streaming output of an indented JSON array | Simon Willison’s TILs
August 29, 2023 - Loop through each object in the iterator. For each one, output a 2-space indented representation of it using json.dumps() - and use textwrap.indent() to indent that by an additional two spaces.
🌐
Appdividend
appdividend.com › pretty-print-json-in-python
How to Pretty Print JSON in Python
June 10, 2025 - If you have JSON data and want to write it in an indented and proper format to a file, you can do so by using the json.dump() method with an indent argument.