PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » JSON » Python PrettyPrint JSON Data

Python PrettyPrint JSON Data

Updated on: May 14, 2021 | Leave a Comment

PrettyPrint is useful to display JSON in an easy-to-read (for human readers) format. When we say PrettyPrinting JSON in Python, we consider primarily for indentation, key-value separators, and whitespace.

Scenarios where we need JSON PrettyPrinting In Python:

  • Write PrettyPrinted JSON formatted data into a file
  • Prettyprint JSON file: Let’s say you have a JSON file that is huge and not correctly indented, and you want to prettyprint it
  • Prettyprint JSON formatted string

Further Reading:

  • Solve Python JSON Exercise to practice Python JSON skills
Python JSON PrettyPring explained
Python JSON PrettyPring explained

Write Indented and Pretty-printed JSON data into a file

In real-world cases, we deal with extensive JSON data. When we write JSON data into a file, we must make sure that the JSON data is readable and well organized, so whosever consuming it have a better understanding of the structure of JSON.

Using the json.dump() method of Python json module, we can write prettyprinted JSON into the file. The json.dump() method provides the following parameters to pretty-print JSON data.

The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json.dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn’t use indentations and writes all data on a single line, which is not readable.

The separator parameter:  You can specify any separator between JSON key and value. The default separator is (', ', ': '). For example, if you specify separators such as (', ', ' : '), JSON will look like this.

{
    "key1" : "value2",
    "key2" : "value2"
}

The sort_keys parameter to sort JSON keys alphabetically.

Now, Let see the example.

import json

print("Writing Indented and Pretty-printed JSON formatted data into a file")

student = {
    "id": 1,
    "name": "Jessa Duggar",
    "class": 9,
    "attendance": 75,
    "subjects": ["English", "Geometry"],
    "email": "jessa@pynative.com"
}

with open("studentWithoutPrettyPrint.json", "w") as write_file:
    json.dump(student, write_file)
print("Done writing JSON data into file without Pretty Printing it")

with open("studentWithPrettyPrint1.json", "w") as write_file:
    json.dump(student, write_file, indent=4)
print("Done writing PrettyPrinted JSON data into file with indent=4")

with open("studentWithPrettyPrint2.json", "w") as write_file:
    json.dump(student, write_file, indent=0)
print("Done writing PrettyPrinted JSON data into file with indent=0")

with open("studentWithPrettyPrint3.json", "w") as write_file:
    json.dump(student, write_file, indent=4, sort_keys=True)
print("Done writing Sorted and PrettyPrinted JSON data into file")

Output:

Writing Indented and Pretty-printed JSON formatted data into a file
Done writing JSON data into file without Pretty Printing it
Done writing PrettyPrinted JSON data into file with indent=4
Done writing PrettyPrinted JSON data into file with indent=0
Done writing Sorted and PrettyPrinted JSON data into file

JSON file without Pretty Printing it

{"id": 1, "name": "Jessa Duggar", "class": 9, "attendance": 75, "subjects": ["English", "Geometry"], "email": "jessa@pynative.com"}

Pretty-Printed JSON data into a file with indent=0

{
"id": 1,
"name": "Jessa Duggar",
"class": 9,
"attendance": 75,
"subjects": [
"English",
"Geometry"
],
"email": "jessa@pynative.com"
}

Pretty-Printed JSON data into a file with indent=4

{
    "id": 1,
    "name": "Jessa Duggar",
    "class": 9,
    "attendance": 75,
    "subjects": [
        "English",
        "Geometry"
    ],
    "email": "jessa@pynative.com"
}

After writing Pretty-Printed JSON data into a file with indent=4 and sorting keys.

{
    "attendance": 75,
    "class": 9,
    "email": "jessa@pynative.com",
    "id": 1,
    "name": "Jessa Duggar",
    "subjects": [
        "English",
        "Geometry"
    ]
}

Remember:

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. For example, when we specify indent=4, Python uses four spaces for indentation.

An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as \t), that string is used to indent each level.

Read and PrettyPrint JSON file from Python

Let’s assume you have a large JSON file not correctly indented, and you want to prettyprint it. You can display prettyprinted JSON in Python using two ways. Let see each one by one.

We are using the “student.json” file stored on my computer for this example. This file contains the following data.

{"id": 1, "name": "Jessa Duggar", "class": 9, "attendance": 75, "subjects": ["English", "Geometry", "Physics", "World History"], "email": "jess@example.com"}

We need to follow the below steps:

  • Read the JSON file first using json.load() method.
  • Use json.dumps() method to prettyprint JSON properly by specifying indent and separators. The json.dumps() method returns prettyprinted JSON data in string format.
  • Print final JSON

Let’s see the example now.

import json

with open("student.json", "r") as read_file:
    print("Read JSON file")
    student = json.load(read_file)

    print("Before Pretty Printing JSON Data")
    print(student)

    print("\n")

    PrettyJson = json.dumps(student, indent=4, separators=(',', ': '), sort_keys=True)
    print("Displaying Pretty Printed JSON Data")
    print(PrettyJson)

Output:

Read JSON file

Before Pretty Printing JSON Data
{'id': 1, 'name': 'Jessa Duggar', 'class': 9, 'attendance': 75, 'subjects': ['English', 'Geometry', 'Physics', 'World History'], 'email': 'jess@example.com'}

Displaying Pretty Printed JSON Data
{
    "attendance": 75,
    "class": 9,
    "email": "jess@example.com",
    "id": 1,
    "name": "Jessa Duggar",
    "subjects": [
        "English",
        "Geometry",
        "Physics",
        "World History"
    ]
}

Use pprint module to pretty-print JSON

The pprint module provides the capability to “pretty-print” any Python data structures. Now, let’s see how to use the pprint module to pretty-print JSON data.

The pprint.pprint() function print the formatted representation of a JSON on the configured stream, followed by a newline

  • Construct a PrettyPrinter instance first by configuring indent and width values. Also, set compact=False.
  • Read the JSON file using json.load() method.
  • Pass JSON data to pprint.pprint() function

Now, Let’s see the demo.

import json
import pprint

with open("studentWithoutPrettyPrint.json", "r") as read_file:
    print("Read JSON file")
    student = json.load(read_file)

    print("Before Pretty Printing JSON Data")
    print(student)

    print("\n")

# construct PrettyPrinter first
pp = pprint.PrettyPrinter(indent=4, width=80, compact=False)

print("Pretty Printing JSON Data using pprint module")
pp.pprint(student)

Output:

Read JSON file

Before Pretty Printing JSON Data
{'id': 1, 'name': 'Jessa Duggar', 'class': 9, 'attendance': 75, 'subjects': ['English', 'Geometry', 'Physics', 'World History'], 'email': 'jess@example.com'}

After Pretty Printing JSON Data using pprint module
{   'attendance': 75,
    'class': 9,
    'email': 'jess@example.com',
    'id': 1,
    'name': 'Jessa Duggar',
    'subjects': ['English', 'Geometry', 'Physics', 'World History']}

Note: Use print only to display JSON data on the console. Never use its output to write JSON into a file.

Pretty-print JSON from the command line

Python provides The json.tool module to validate and pretty-print JSON objects from the command line. We can do the following tasks using its module’s command-line interface.

Display JSON string as pretty-printed JSON on sys.stdout

Run a below command on the command line. Here we are validating the Python dictionary and pretty-printing it in a JSON formatted string.

echo {"id": 1, "name": "Jessa Duggar"} | python -m json.tool

Output:

{
    "id": 1,
    "name": "Jessa Duggar"
}

We can also use different command-line options of json.tool module to Prettyprint and validate JSON. Let’s see those.

Pass JSON file name, pretty-print it on sys.stdoutth

The json.tool module provides a infile command-line option to specify a JSON file name to be pretty-printed.

File content before running the following command

{"id": 1, "name": "Jessa Duggar", "class": 9, "attendance": 75, "subjects": ["English", "Geometry", "Physics", "World History"], "email": "jess@example.com"}
python -m json.tool studentWithoutPrettyPrint.json

Output:

{
    "id": 1,
    "name": "Jessa Duggar",
    "class": 9,
    "attendance": 75,
    "subjects": [
        "English",
        "Geometry",
        "Physics",
        "World History"
    ],
    "email": "jess@example.com"
}

As you can see in the command output, the file content is pretty-printed.

Pass JSON file, PrettyPrint it and write it in another file

The json.tool module also provides a outfile command-line option to write validated and pretty-printed JSON data into a new file.

Command:

python -m json.tool studentWithoutPrettyPrint.json newFile.json

Result:

New PrettyPrinted JSON File
New PrettyPrinted JSON File

A new file is created, which contains prettyPrinted JSON data.

So What Do You Think?

I want to hear from you. What do you think of this article? Or maybe I missed one of the ways to PrettyPrint JSON data in Python. Either way, let me know by leaving a comment below.

Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.

Filed Under: Python, Python JSON

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python JSON

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Python Python JSON
TweetF  sharein  shareP  Pin

  Python JSON

  • Python JSON Guide
  • JSON Serialization
  • JSON Parsing
  • JSON Validation
  • PrettyPrint JSON
  • Make Python Class JSON serializable
  • Convert JSON Into Custom Python Object
  • Python JSON Unicode
  • Parse JSON using Python requests
  • Post JSON using Python requests
  • Serialize DateTime into JSON
  • Serialize Python Set into JSON
  • Serialize NumPy array into JSON
  • Parse multiple JSON objects from file
  • Parse Nested JSON
  • Python JSON Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com