You can use json.dump() method:

with open("text", "w") as outfile:
    json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
Answer from alecxe on Stack Overflow
🌐
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
Using json.dumps(), convert it to a string. Set the indent option to 4. Print the result. ... Our website uses cookies. By using this website, you agree to their use in accordance with the browser settings.You can modify your browser ...
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
indent (int | str | None) – If a positive integer or string, JSON array elements and object members will be pretty-printed with that indent level. A positive integer indents that many spaces per level; a string (such as "\t") is used to indent ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pretty-print-json
Python - Pretty Print JSON - GeeksforGeeks
July 23, 2025 - Like json.dumps() method, it has the indents and separator parameters to write beautified JSON. ... import json data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]}, {"studentid": 2, "name": "PQR", "subjects": ["Java", ...
🌐
PYnative
pynative.com › home › python › json › python prettyprint json data
Python PrettyPrint JSON Data
May 14, 2021 - We can use the indent parameter of json.dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn’t use indentations and writes all data on a single line, which is not readable.
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write JSON data to a file in Python | Sentry
For example: Click to Copy · Click ... as f: json.dump(data, f, indent=4) The indent keyword argument specifies the number of spaces to use for indentation when formatting the JSON data....
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
September 16, 2025 - You’ll learn how to serialize custom Python objects, process massive JSON files without running out of memory, and leverage high-performance alternative libraries to speed up your applications. ... Use indent and sort_keys in json.dumps() to instantly make your JSON output readable and ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to pretty print a json file in python?
How to Pretty Print a JSON file in Python? - Spark By {Examples}
May 31, 2024 - By default, the output JSON is compact and hard to read. You can make the JSON file more readable by using the indent parameter in the json.dump() method. The indent parameter specifies the number of spaces to use for indentation.
Find elsewhere
🌐
Pradet
quentin.pradet.me › blog › indenting-json-in-python.html
Indenting JSON in Python
In other words, I had to write a JSON encoder that would look exactly like a JSON encoder, except that it would not escape anything. (Note that this requires trusting the input.) The interesting part was indentation: I wanted the result to be indented with two spaces at each level, as if I had used json.dumps(indent=2).
🌐
GeeksforGeeks
geeksforgeeks.org › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
Another way of writing JSON to a file is by using json.dump() method The JSON package has the "dump" function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.
Published   May 29, 2025
🌐
HowToDoInJava
howtodoinjava.com › home › python json › python – write json to a file
Python - Write JSON to a File - Write dict to a File
October 2, 2022 - import json # Python object py_dict = { "id" : 1 } # Write to File with open('users.json', 'w') as json_file: json.dump(py_dict, json_file, indent=4, sort_keys=True, separators=(',',':')) The json.dump() serializes a Python object as a JSON ...
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.

🌐
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

🌐
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 - We use the with keyword to create a writeable file, where we then dump our object into, using the indent= keyword · The context manager will handle closing the file once it’s done saving the file for us.
🌐
Codingem
codingem.com › home › python pretty print json
Python Pretty Print JSON [with 3 Examples] - codingem.com
January 23, 2023 - import json #Initialize JSON data as a JSON string json_data = '[ {"name": "Jack", "topics": ["Python", "Data Structures and Algorithms"]}, \ { "name": "Sofie", "topics": ["Java", "Functional Programming"]} ]' #Convert JSON to Python object obj = json.loads(json_data) #Python pretty print JSON json_formatted_str = json.dumps(obj, indent=4) print(json_formatted_str) ... [ { "name": "Jack", "topics": [ "Python", "Data Structures and Algorithms" ] }, { "name": "Sofie", "topics": [ "Java", "Functional Programming" ] } ] As you can see, now the JSON data is nicely formatted. This JSON is really easy to read as opposed to the lengthy one-liner JSON. You can write a pretty printed JSON object to a text file using json.dump() method.
🌐
TestMu AI Community
community.testmuai.com › ask a question
How do I write JSON data to a file in Python? - TestMu AI Community
December 5, 2024 - I have JSON data stored in a dictionary, and I want to write it to a file. I tried the following approach: f = open('data.json', 'wb') f.write(data) However, this results in the error: TypeError: must be string or buf…
🌐
Newtum
blog.newtum.com › write-json-to-file-in-python
Write JSON to File in Python (With Examples & Tips)
January 19, 2026 - import json with open("data.json", "r") as file: existing_data = json.load(file) existing_data["experience"] = "5 years" with open("data.json", "w") as file: json.dump(existing_data, file, indent=4) ... This method ensures data integrity while ...
🌐
W3Schools
w3schools.io › file › json-python-read-write
How to read and write JSOn file in Python - w3schools
How do you sort keys of the json content and write to the file? Supply the sort_keys=True parameter to json dumps method ... Open the file with encoding='utf-8'. Supply ensure_ascii=False parameter to json.dumps method ... import json with open('test.json', 'w', encoding='utf-8') as filehandler: json.dump(employee, filehandler, ensure_ascii=False, indent=4) This example reads the json data from a file in Python.
🌐
Milddev
milddev.com › python-write-json-to-file
Write JSON to File in Python
Writing JSON to a file in Python is simple at first glance, but mastering it opens up safe data storage, readable configurations, and reliable APIs. We covered the basics with json.dump, improved readability using indent and separators, handled complex data via custom encoders, and implemented error strategies to prevent crashes. Along the way, we learned how to optimize for performance with streaming writes and atomic file replaces.