Textlogo_codingem_white

Programming tips for everyone

Python: JSON Pretty Print

JSON stands for JavaScript Object Notation. It is a popular text-based data format used broadly to represent structured data. Almost every programming language supports it. Python is no exception.

Commonly, JSON is used to transmit data between the client and a server. To save some bandwidth the JSON payload is sent in an optimized format. The problem with this format is it’s very daunting to read in Python. JSON pretty print can help in this case by properly indenting, white spacing, and separating the object.

In Python, you can use json.dumps() method to pretty-print JSON:

json.dumps(indent,separator)


Python JSON Pretty Print

Python JSON pretty print is possible using the built-in json module. It allows working with JSON data in Python. There are three cases in which you may want to use the pretty-print functionality:

  1. Pretty-print a JSON string.
  2. Write pretty-printed JSON to a file.
  3. Read JSON file and pretty-print.


Let’s next go through each possibility by showing an example.


1. Pretty-Print a JSON String

First, you need json.loads() to convert the JSON String to a Python object. Then, to pretty print this JSON object, use the json.dumps()

Syntax of pretty print:

json.dumps(indent,separator)


  • The parameter indent specifies the number of spaces
  • The separator specifies the separator between the keys and values.


By default, a comma separates key-value pairs. If the indent parameter is negative, 0 or an empty string then there are no indentations. By default, indent is None and the data is represented in a single line.


For instance:

#Import json module
import json
 
#Initialize JSON data as a JSON string
json_data = '[ {"name": "Jack", "topics": ["Python", "Data Structures and Algorithms"]}, \
                 { "name": "Sofie", "topics": ["Java", "Functional Programming"]} ]'
 
#Convert JSON to Python object
obj = json.loads(json_data)
 
#Python pretty print JSON
json_formatted_str = json.dumps(obj, indent=4)
print(json_formatted_str)


Output:

[
    {
        "name": "Jack",
        "topics": [
            "Python",
            "Data Structures and Algorithms"
        ]
    },
    {
        "name": "Sofie",
        "topics": [
            "Java",
            "Functional Programming"
        ]
    }
 ]


Now the readability of the JSON string is way better.

2. Write Pretty-Printed JSON to a File

You can write a pretty printed JSON object to a text file using json.dump() method. Similar to json.dumps() method, it has the indents and separator parameters to write beautified JSON. Let’s see an example:

#Import json module
import json

#Initialize JSON data as a JSON string
json_data = [{"name": "Jack", "topics": ["Python", "Data Structures and Algorithms"]},
             {"name": "Sofie", "topics": ["Java", "Functional Programming"]}]

#Write pretty print JSON data to file
with open("example.json", "w") as write_file:
    json.dump(json_data, write_file, indent=4)


Output (file):


3. Read JSON File and Pretty-Print

You can read a JSON object from a file or URL with the json.load() method. Then just use the json.dumps() method to pretty print the JSON. 

To demonstrate, let’s read the file you just created in the previous example:

import json

with open("example.json", "r") as read_file:
    obj = json.load(read_file)
    print(json.dumps(obj, indent=4))

Output:

[
     {
         "name": "Jack",
         "topics": [
             "Python",
             "Data Structures and Algorithms"
         ]
     },
     {
         "name": "Sofie",
         "topics": [
             "Java",
             "Functional Programming"
         ]
     }
 ]



Conclusion

JSON is a commonly used text-based data format that works well with Python. In order to improve JSON readability, you can use JSON pretty print. Pretty printing can be useful in these three situations:

  • Print a JSON string
  • Save JSON data to a file
  • Read JSON data from a file


Thanks for reading. Happy coding!

You May Also Like

Formatted String in Python

Lambda Expressions in Python

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Favorites