Table of contents
1.
Introduction
2.
What is JSON?
3.
json.dumps() in Python
4.
Pretty Print JSON String
5.
Pretty-Printed JSON Data into a File with indent=0
6.
Write Pretty Print JSON Data to File
7.
Reading JSON Data and Pretty Print It
8.
Using pprint Module to Pretty-Print JSON to Print Our JSON Format
9.
Pretty-Print JSON from the Command Line
10.
Using Python’s JSON Tool
11.
Using jq Command
12.
Frequently Asked Questions
12.1.
What is the advantage of using JSON in web applications?
12.2.
Can JSON support comments within the data?
12.3.
How can I handle large JSON files efficiently?
13.
Conclusion
Last Updated: May 29, 2024
Easy

Json Pretty

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read & write. It is also easy for machines to parse & generate. JSON is often used to transmit data between a server & a web application. 

Json Pretty

In this article, we will learn about JSON pretty printing in Python. We will discuss what JSON is, how to use the json.dumps() method to pretty print JSON strings, how to write pretty printed JSON data to a file, how to read JSON data from a file & pretty print it, & how to use the pprint module to pretty print JSON. 

What is JSON?

JSON stands for JavaScript Object Notation. It is a way to store information in an organized, easy-to-access manner. JSON gives us a human-readable collection of data that we can access in a really logical manner. Unlike complex data formats, JSON is formatted in a way that is similar to the objects in programming languages, specifically JavaScript. It uses text format, which is easy to send & receive across networks.

JSON is built on two structures:

  1. A collection of key/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
     
  2. An ordered list of values, which is often realized as an array, vector, list, or sequence.
     

This format is not only easy to read but also easy to write. Its simplicity is what makes it so popular for web applications, configurations, and data interchange between servers and client apps. Whether you're storing configuration settings or sending data from a server to a client, JSON is a reliable, lightweight choice to handle this data efficiently.

json.dumps() in Python

In Python, the json.dumps() function is one of the primary tools you'll use to work with JSON data. The name "dumps" is short for "dump string," and as the name suggests, this function converts a Python object into a JSON-formatted string. This is especially useful when you need to serialize Python objects for network transmission or for saving to a file in a format that can be read by other programming languages.

Here's a straightforward example to demonstrate how json.dumps() works:

import json
# Example Python dictionary
data = {
  "name": "Sinki",
  "age": 24,
  "city": "Bangalore"
}
# Convert Python dictionary to JSON string
json_string = json.dumps(data, indent=4)
print(json_string)


In this example:

  • We first import the json module, which gives us access to the dumps method.
     
  • We define a Python dictionary named data with some key-value pairs.
     
  • We use json.dumps() to convert this dictionary into a JSON string. The parameter indent=4 makes the JSON string more readable by adding whitespace.
     

This function is particularly useful when data needs to be exchanged between a server and a web application. JSON is text, and text can be easily passed back & forth without compatibility or data loss issues.

Pretty Print JSON String

When working with JSON data, readability can be as important as functionality, especially during debugging or when sharing code with others. The term "pretty print" refers to displaying JSON data in a way that is easy for humans to read. Python’s json module provides a very straightforward way to achieve this using the same json.dumps() function with an additional argument called indent.

Here's how you can pretty print a JSON string in Python to enhance its readability:

import json
# Example Python dictionary
data = {
  "name": "Sinki",
  "age": 24,
  "city": "Bangalore",
  "hobbies": ["reading", "cycling", "hiking"]
}
# Convert Python dictionary to a pretty-printed JSON string
json_string_pretty = json.dumps(data, indent=4)
print(json_string_pretty)


In the code above:

  • The indent parameter in the json.dumps() function is used to format the JSON string. Setting indent=4 adds four spaces for each level of nesting in the JSON data.
     
  • This results in a JSON string that is not only easy to read but also neatly organized, with each nested element indented more than its parent, making the hierarchy clear.


This method is incredibly useful when you need to review complex data structures quickly or share them with team members who may need to understand the structure at a glance.

Pretty-Printed JSON Data into a File with indent=0

Writing pretty-printed JSON data to a file involves a similar approach to printing it to the console, but instead, you direct the output to a file. This can be particularly useful for logging or saving configurations in a format that's easy to edit manually. Interestingly, you might choose to use indent=0, which minimally spaces elements in the JSON data, providing some structure without excessive whitespace.

Here’s how you can write a JSON object to a file with minimal indentation:

import json
# Example Python dictionary
data = {
  "name": "Sinki",
  "age": 24,
  "city": "Bangalore",
  "hobbies": ["reading", "cycling", "hiking"]
}
# Writing JSON data to a file with minimal indentation
with open('data.json', 'w') as file:
    json.dump(data, file, indent=0)


In this code:

  • We open a file named data.json in write mode. If data.json does not exist, it will be created. If it already exists, its content will be overwritten.
     
  • The json.dump() function is used here instead of json.dumps(). The dump function is designed to output JSON data directly to a file or a file-like object.
     
  • We use indent=0 to add a minimal amount of spacing in the structure, which is just enough to keep the elements separated but does not add multiple spaces or new lines like a higher indent value would.
     

This functionality is essential when handling data that benefits from being in a structured yet compact format, such as configuration files or data logs that are frequently accessed and updated programmatically.

Write Pretty Print JSON Data to File

Writing JSON data in a pretty-printed format to a file not only makes the data easy to read but also simplifies the process of manual editing and review by humans. This is particularly useful in scenarios where JSON files serve as part of configuration management or data sharing between different parts of an application or even different applications.

Here's how to write pretty-printed JSON data to a file using Python:

import json
# Example Python dictionary
data = {
  "name": "Sinki",
  "age": 24,
  "city": "Bangalore",
  "hobbies": ["reading", "cycling", "hiking"]
}
# Writing JSON data to a file with pretty print
with open('pretty_data.json', 'w') as file:
    json.dump(data, file, indent=4)


In this example:

  • We use the open() function to create a file named pretty_data.json in write mode. If this file doesn't exist, Python will create it for us. If it does exist, its contents will be replaced.
     
  • The json.dump() function takes the Python dictionary and writes it to the file specified. The indent=4 parameter tells the JSON library to format the data with 4 spaces for each level of nesting, which greatly improves the readability of the file.
     

By storing JSON data in this format, anyone who needs to view or edit the file can easily understand the structure and content without needing to reformat it themselves.

Reading JSON Data and Pretty Print It

Reading JSON data from a file and displaying it in a pretty-printed format is an essential skill for developers, especially when dealing with configurations or data exchange between systems. This process involves two main steps: reading the JSON file into a Python object, and then using the json.dumps() function to convert it back into a string with indentation for readability.

Here’s how you can read JSON data from a file and pretty print it using Python:

import json
# Reading JSON data from a file
with open('pretty_data.json', 'r') as file:
    data = json.load(file)
# Pretty-printing the JSON data
print(json.dumps(data, indent=4))


In this code:

  • We first open the file pretty_data.json for reading ('r'). This file contains JSON data stored in a previous example.
     
  • The json.load() function is used to load the JSON data from the file into a Python dictionary. This allows us to manipulate or just read the data as needed within our application.
     
  • Finally, we use json.dumps() with the indent=4 parameter to convert the dictionary back into a JSON string, which is then printed in a format that is easy to read, with each level of nesting indented by four spaces.
     

This method is highly effective for verifying data integrity, debugging, or simply enhancing the visibility of structured data. It ensures that anyone who needs to review the JSON content can do so without dealing with a continuous block of text.

Using pprint Module to Pretty-Print JSON to Print Our JSON Format

While Python's json module is excellent for handling JSON data, the Python standard library also offers another tool, the pprint module, designed for making the output of data structures easier to read. This can be particularly useful when you want to print JSON data in a way that is visually appealing and easier to understand, especially when dealing with complex or nested data.

Here's how to use the pprint module to pretty-print JSON data:

import json
import pprint
# Example JSON data
json_data = {
    "name": "Sinki",
    "age": 24,
    "city": "Bangalore",
    "hobbies": ["reading", "cycling", "hiking"]
}
# Convert JSON data to a string to use with pprint
json_string = json.dumps(json_data)
# Create a PrettyPrinter object and use it to print the JSON data
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json_string)


In this example:

  • We first import both json and pprint modules.
     
  • We convert our JSON data into a string using json.dumps() because pprint works best with string inputs when dealing with JSON.
     
  • We then create a PrettyPrinter object, specifying an indent of 4, which defines how many spaces to use when nesting elements.
     
  • The pp.pprint() method is then called to print the JSON string in a formatted style.
     

The pprint module is an excellent choice for developers who need an easy way to display complex data structures during debugging or presentation of data. It provides a clean, readable format by organizing the output into lines and keeping related items together.

Pretty-Print JSON from the Command Line

Pretty-printing JSON directly from the command line is a useful skill for quickly formatting or inspecting JSON files without needing to write additional code or open an IDE. This can save time, especially during development or when working on server configurations. Here’s how you can pretty-print JSON data from the command line using Python:

Using Python’s JSON Tool

Python comes with a built-in JSON tool that can be used directly from the command line. You simply need to echo the JSON string or pipe a file containing JSON data into Python’s JSON tool as shown below:

echo '{"name": "Sinki", "age": 24, "city": "Bangalore"}' | python -m json.tool
or for files:
cat data.json | python -m json.tool


These commands:

  • Use echo to send a JSON string directly into Python’s JSON tool, or cat to pass the contents of a JSON file.
     
  • The python -m json.tool command reads the JSON data and prints it in a nicely formatted and indented style directly in your command line interface.

Using jq Command

jq is a powerful command-line JSON processor. If you frequently work with JSON, it might be worthwhile to install jq which provides more advanced features for manipulating and pretty-printing JSON data.

cat data.json | jq .


This command:

  • Uses jq ., where the period . represents the filter for all data inside the JSON file. It pretty-prints the entire content of data.json.


Both methods are effective for different needs: Python’s JSON tool is great for quick checks and is readily available with Python installations, while jq offers more robust handling and manipulation capabilities for JSON data.

Frequently Asked Questions

What is the advantage of using JSON in web applications?

JSON is lightweight and easy to parse, making it ideal for data interchange between clients and servers. It simplifies data manipulation, leading to faster response times in web applications.

Can JSON support comments within the data?

No, JSON does not support comments directly within the data format. This is intended to keep the data format minimal and free from extraneous information.

How can I handle large JSON files efficiently?

For large JSON files, consider using streaming JSON parsers like ijson in Python, which allow you to process the file incrementally instead of loading it all into memory at once.

Conclusion

In this article, we have learned the basics of JSON and its applications, how to use Python's json.dumps() to create JSON formatted strings, and various methods to pretty-print JSON both in Python and from the command line. We also discussed how to read, write, and pretty-print JSON data efficiently, making use of both built-in Python capabilities and external tools like jq for more complex tasks. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass