Skip to content

Python write JSON to file pretty

  • by

Use the optional argument indent in the dumps() function to write JSON to file pretty in Python. The json.dump() method provides the following parameters to pretty-print JSON data.

json.dumps(mydata, indent=4)

The indent parameter specifies the spaces used at the beginning of a line.

Python writes JSON to files pretty example

Simple example code Pretty Printed JSON formatted data into a file.

import json

student = {
"id": 1,
"name": "John Duggar",
"class": 9,
"attendance": 75,
"subjects": ["English", "Geometry"],
"email": "[email protected]"
}

with open("stu.json", "w") as write_file:
json.dump(student, write_file, indent=4)

Output:

Python write JSON to file pretty

Read and PrettyPrint JSON file from Python

  • Read the JSON file first using json.load() method.
  • Use json.dumps() method to prettyprint JSON properly by specifying indent and separators. The json.dumps() method returns prettyprinted JSON data in string format.
  • Print final JSON
import json

with open("stu.json", "r") as read_file:
student = json.load(read_file)

res = json.dumps(student, indent=4, separators=(',', ': '), sort_keys=True)
print(res)

Output:

{
    "attendance": 75,
    "class": 9,
    "email": "[email protected]",
    "id": 1,
    "name": "John Duggar",
    "subjects": [
        "English",
        "Geometry"
    ]
}

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading