How to Format a JSON File in Python?

Estimated read time 2 min read

Formatting a JSON file in Python involves arranging the data in a structured and readable way. Python’s built-in json module provides the dumps and dump methods that can be used to format a JSON file.

Here is an example of formatting a JSON file in Python:

import json

# Example JSON data
data = {"name": "John", "age": 30, "city": "New York"}

# Using dumps() to format the JSON data
formatted_data = json.dumps(data, indent=4)

# Print the formatted data
print(formatted_data)

# Using dump() to format and write the JSON data to a file
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

In the above example, the json.dumps() method is used to format the data dictionary and store it in the formatted_data variable. The indent parameter is set to 4 to add four spaces for each level of indentation.

The formatted JSON data is then printed to the console using print().

The json.dump() method is used to format and write the JSON data to a file named “data.json”. The indent parameter is again set to 4 to format the data with four spaces for each level of indentation. The file is opened in write mode with open() and the json.dump() method is used to write the formatted JSON data to the file. Finally, the file is closed with f.close().

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply