AppDividend
Latest Code Tutorials

How to Pretty Print JSON File in Python

0

When we need to dump a dictionary into json format, that’s where the concept of Pretty Print Json comes into the picture where we can display the JSON loaded into a presentable format.

Pretty Print JSON File in Python

To pretty print json files in Python, pass the indent parameter in the json.dumps() function. The json.dumps() is an inbuilt Python method that converts an object into a JSON string. If you are working with an external json file, then you can use the json.load() function to load the file.

The json.load() is an inbuilt method that accepts a file object and returns the json object. The keys are strings, and the values are the JSON data types.

Steps to pretty print json file in Python

Step 1: Let’s define an external json file.

If you are dealing with json file, then you need to load the file using json.load() function.

If you are dealing with json text, then you need to load the text using json.loads() function.

You can define an external file, or you can define a static JSON string. Let’s use the external json file.

Our file name is new_file.json.

{
  "data": [
    {
      "color": "red",
      "value": "#f00"
    },
    {
      "color": "green",
      "value": "#0f0"
    },
    {
      "color": "blue",
      "value": "#00f"
    },
    {
      "color": "black",
      "value": "#000"
    }
  ]
}

Step 2: Read json file.

  1. Import the json module.
  2. Open data.json using the with() method.
  3. Load the JSON object inside the data.json file using the json.load() method.
  4. Print out the values of the JSON object returned from the load() method.
import json

with open('new_file.json', 'r') as handle:
    parsed = json.load(handle)

All the content of the new_file.json is stored inside the parsed variable.

Now, to print the pretty json, use the json.dumps() method and pass the indent parameter and assign a suitable value to prettify your json.

import json

with open('new_file.json', 'r') as handle:
    parsed = json.load(handle)
    print(json.dumps(parsed, indent=4, sort_keys=True))

Output

{
    "data": [
        {
            "color": "red",
            "value": "#f00"
        },
        {
            "color": "green",
            "value": "#0f0"
        },
        {
            "color": "blue",
            "value": "#00f"
        },
        {
            "color": "black",
            "value": "#000"
        }
    ]
}

We passed indent’s value to 4. You can pass any integer value as per your requirement.

If we pass the indent = 2, then it will return the following indentation.

import json

with open('new_file.json', 'r') as handle:
    parsed = json.load(handle)
    print(json.dumps(parsed, indent=2, sort_keys=True))

Output

{
  "data": [
    {
      "color": "red",
      "value": "#f00"
    },
    {
      "color": "green",
      "value": "#0f0"
    },
    {
      "color": "blue",
      "value": "#00f"
    },
    {
      "color": "black",
      "value": "#000"
    }
  ]
}

You can clearly see the difference between the above two outputs based on the value of the indentation.

Let’s take another example and define a static json string and use the json.dumps() method to prettify the json string.

import json

json_str = '["Amazon", {"AWS":["Andy Jassy", "New CEO", 2.0]}]'
parsed = json.loads(json_str)
print(json.dumps(parsed, indent=4, sort_keys=True))

Output

[
    "Amazon",
    {
        "AWS": [
            "Andy Jassy",
            "New CEO",
            2.0
        ]
    }
]

You can see that the printed json is pretty, and 4 is a good indent value. It is clear and concise.

That is it for Pretty Print JSON in Python.

See also

Convert Python JSON to Dict

Python JSON to Dictionary

Python JSON Parse

Handle JSON NULL in Python

Python JSON to CSV

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.