How to Pretty Print JSON Serialized Data in Python?

Estimated read time 1 min read

You can use the json module in Python to pretty print JSON serialized data. The json.dumps() function provides an optional argument indent that you can use to specify the number of spaces to use for indentation. Here’s an example:

import json

data = {"name": "John", "age": 30, "city": "New York"}

# Serialize the data to a JSON string with pretty printing
pretty_json = json.dumps(data, indent=4)

# Print the pretty-printed JSON

In this example, the data dictionary is serialized to a JSON string with pretty printing using the json.dumps() function with an indent argument of 4. The resulting pretty-printed JSON is stored in the pretty_json variable, which is then printed to the console using the print() function.

The output of this example would be:

    "name": "John",
    "age": 30,
    "city": "New York"

As you can see, the resulting JSON is indented with four spaces for each level of nesting, making it much easier to read than a single-line JSON string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply