How to Pretty Print a JSON String in Python

Pretty-printing JSON strings in Python is simple with the help of the built-in json module. By using the json.dumps() method with an indentation parameter, you can display JSON data in a more readable format. Here’s a step-by-step guide:

  1. Convert JSON String to a Python Object:
    Start by using the json.loads() method to parse the JSON string into a Python dictionary or list.
  2. Pretty Print JSON with Indentation:
    Use the json.dumps() method to convert the Python object back into a JSON string, and specify the indent parameter to define the level of indentation for readability. If you don’t use this parameter, the JSON data will be output as a compact, single-line string.
    • Default Output: Without the indent parameter, the JSON is compact with no extra spaces or line breaks.
    • Customizing Indentation: Setting indent=2 or any positive number creates a structured format. If you set indent=0 or pass an empty string, the output will still be on a single line but with newlines inserted.

Here’s an example of pretty-printing a minified JSON string:

import json

# Minified JSON string
json_data = '{"name": "Dharmender", "age": 25, "city": "Bangalore"}'

# Convert to Python object
parsed_data = json.loads(json_data)

# Pretty print with indentation
pretty_json = json.dumps(parsed_data, indent=4)
print(pretty_json)

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, language-independent format designed for data storage and exchange. It is widely used for transferring data between servers and clients via REST APIs and between servers themselves.
Many programming languages, such as Python, JavaScript, Java, C++, PHP, and Go, support JSON through built-in libraries or external packages. JSON files typically have a .json extension.

Example Output

Here’s how the output will look with the example code:

{
    "name": "Dharmender",
    "age": 25,
    "city": "Bangalore"
}

By formatting JSON data like this, developers can better debug and understand the structure of the data being handled.

Why Pretty Print JSON?

  • Readability: Makes it easier to spot errors or inconsistencies.
  • Debugging: A clear structure simplifies debugging during development.
  • Presentation: Readable JSON is useful for logs, documentation, or sharing data with others.

This post  provides a quick way to improve your JSON handling skills in Python, enhancing both efficiency and readability.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *