How To Pretty-Print Json Using Python

When working with JSON (JavaScript Object Notation) in Python, it may be helpful to pretty-print the JSON data for better readability and easier debugging.

Pretty printing means formatting the JSON in a more human-friendly way, with proper indentation and line breaks. In this tutorial, we will explore how to pretty-print JSON data using Python.

Step 1: Import the JSON module

First, you need to import the json module that comes built-in with Python. You don’t need to install any additional packages.

Step 2: Load a JSON string or file

You can either start with a JSON string or load a JSON file. In this tutorial, we’ll use an example JSON string.

To load JSON data from a file, use the following code:

Step 3: Pretty-print the JSON data

To pretty-print the JSON data, you can use the json.dumps() function, which takes two parameters: the JSON data, and the indent value. The indent value specifies how many spaces to use for indentation.

The above code will output the JSON data in a nicely formatted way, like this:

{
    "name": "John",
    "age": 30,
    "city": "New York",
    "hobbies": [
        "reading",
        "gaming",
        "coding"
    ]
}

Full code

Here’s the complete code to pretty-print JSON data using Python:

Conclusion

In this tutorial, we learned how to pretty-print JSON data using Python’s built-in json module. The steps are simple: import the json module, load the JSON data, and then use the json.dumps() function with an appropriate indent value. This will help you work with JSON data more efficiently and make it easier to read and debug.