Pretty print a JSON file in Python
This post will discuss how to pretty-print a JSON file in Python.
1. Using pprint.pprint() function
The most common approach to pretty-print a JSON file in Python is using the built-in module pprint, which provides the capability to print the formatted representation of JSON data.
|
1 2 3 4 5 6 7 8 9 |
import json import pprint with open('data.json', 'r') as f: data = f.read() json_data = json.loads(data) pprint.pprint(json_data) |
2. Using json.dump() function
Another good option to pretty-print a JSON file is using the json.dumps() function, which by default returns the most compact representation of json. For pretty-printing the JSON, you can specify the desired indentation using the indent parameter.
1. A positive indent level indents that many spaces per level.
|
1 2 3 4 5 6 7 8 |
import json with open('data.json', 'r') as f: data = f.read() json_data = json.loads(data) print(json.dumps(json_data, indent=4)) |
2. If the indent is a string (such as '\t'), that string will indent each level.
|
1 2 3 4 5 6 7 8 |
import json with open('data.json', 'r') as f: data = f.read() json_data = json.loads(data) print(json.dumps(json_data, indent='\t')) |
3. A zero or negative indent level will only insert newlines.
|
1 2 3 4 5 6 7 8 |
import json with open('data.json', 'r') as f: data = f.read() json_data = json.loads(data) print(json.dumps(json_data, indent=0)) |
3. Using simplejson.dump() function
You can also use the simplejson module that works similarly to the json module.
|
1 2 3 4 5 6 7 8 |
import simplejson with open('data.json', 'r') as f: data = f.read() json_data = simplejson.loads(data) print(simplejson.dumps(json_data, indent=4)) |
That’s all about pretty printing a JSON file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)