How to Prettyprint a Json File in Python?

Better Stack Team
Updated on June 19, 2024

You can pretty print a JSON file in Python using the json module's loads() function to parse the JSON data, and then the json.dumps() function with the indent parameter to output it in a readable format. Here's how you can do it:

 
import json

# Load JSON data from a file
with open('file.json', 'r') as file:
    json_data = json.load(file)

# Pretty print the JSON data
pretty_json = json.dumps(json_data, indent=4)

print(pretty_json)

In this code:

  • Replace 'file.json' with the path to your JSON file.
  • json.load(file) reads the JSON data from the file and parses it into a Python object (usually a dictionary or a list of dictionaries).
  • json.dumps(json_data, indent=4) converts the parsed JSON data back into a formatted JSON string with an indentation of 4 spaces, making it more readable.
  • The resulting formatted JSON string is stored in the variable pretty_json, which you can then print or manipulate further as needed.

This will output the JSON data in a nicely formatted, human-readable way.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.