Beginner Level
Intermediate Level
Advanced Level
Introduction
While JSON is easy for machines to read and work with, it can be difficult for humans to parse. In this tutorial, we will explore the PrettyPrint library in Python, which makes it easy to read or display JSON data in a more readable and understandable format. With PrettyPrint, we can convert JSON data into a more organized and structured format, making it much easier to analyze and work with. Whether you're a beginner or an experienced Python programmer, this tutorial will give you all the tools you need to work with JSON data in a more convenient way.
Table of Contents :
- How to write Pretty-printed JSON Data into a File
- PrettyPrint JSON File in Python
- Using pprint Module to Pretty-print JSON
- Pretty-print JSON from the Command Line
How to write Pretty-printed JSON Data into a File :
- To write pretty-printed JSON data to a file, use the
json.dump()
function with theindent
parameter. - The
indent
parameter specifies the number of spaces used for indentation. - Code Sample :
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Writing pretty-printed JSON data to a file
with open('data.json', 'w') as file:
json.dump(data, file, indent=4)
PrettyPrint JSON File in Python :
- To pretty-print JSON data read from a file, use the
json.load()
function to read the data and - the
json.dumps()
function with theindent
parameter to pretty-print it. - Code Sample :
import json
# Reading and pretty-printing JSON data from a file
with open('data.json') as file:
data = json.load(file)
pretty_data = json.dumps(data, indent=4)
print(pretty_data)
Using pprint Module to Pretty-print JSON :
- The
pprint
module can be used to pretty-print JSON data. - Use the
pprint()
function to print the data in a readable format. - Code Sample :
import json
import pprint
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# Pretty-printing JSON data using pprint
pprint.pprint(data, indent=4)
Pretty-print JSON from the Command Line :
- We can pretty-print JSON data from the command line using the
jq
command-line tool. - Install
jq
using your package manager. - Run the
jq
command followed by the input file and the-C
and-M
options. - Example:
$ cat data.json | jq -C -M
Prev. Tutorial : Load json data
Next Tutorial : Python for csv files