To pretty print a JSON file in Python, you can use the json module along with the json.dumps() function. The json.dumps() function allows you to serialize a JSON object to a formatted string with indentation and line breaks.
Here's an example that demonstrates how to pretty print a JSON file:
import json # Load the JSON data from a file with open('your_file.json') as file: data = json.load(file) # Pretty print the JSON data pretty_json = json.dumps(data, indent=4) # Print or save the pretty printed JSON print(pretty_json)
In this example, you need to replace 'your_file.json' with the path to your actual JSON file. The json.load() function is used to load the JSON data from the file into a Python object. Then, json.dumps() is used to convert the object back to a formatted JSON string with an indentation level of 4. Finally, you can either print the pretty printed JSON or save it to a file as per your requirement.
By specifying the indent parameter in json.dumps(), you can control the number of spaces used for indentation. Setting indent to None or 0 will result in compact JSON without any extra whitespace.
Note that if the JSON file is already loaded into a Python object, you can directly pass that object to json.dumps() instead of loading it from a file.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.