JSON Formatter Program in Python

 

 

Introduction

JSON (JavaScript Object Notation) is a widely used format for storing and exchanging data. However, JSON strings often appear in compact and hard-to-read forms. To make these strings easier to understand, we can format them to a readable structure with proper indentation and line breaks. This program demonstrates how to create a Python script that takes a JSON string and formats it for better readability.

Objective

The objective of this program is to provide a clear and simple method to format JSON strings. By the end of this guide, you will have a functional Python program capable of taking compact JSON input and outputting a well-structured and indented JSON representation.

Python Code

import json

def format_json(json_string):
    try:
        # Parse the JSON string into a Python dictionary
        parsed_json = json.loads(json_string)
        # Convert the dictionary back into a formatted JSON string
        formatted_json = json.dumps(parsed_json, indent=4)
        return formatted_json
    except json.JSONDecodeError as e:
        return f"Invalid JSON: {e}"

if __name__ == "__main__":
    # Example JSON string
    raw_json = '{"name": "John", "age": 30, "city": "New York"}'
    print("Original JSON String:")
    print(raw_json)

    print("\nFormatted JSON String:")
    print(format_json(raw_json))

Program Explanation

This Python program uses the json module to handle JSON data. Here’s a breakdown of the program structure:

  • json.loads(): Parses a JSON string and converts it into a Python dictionary.
  • json.dumps(): Converts the Python dictionary back into a JSON string with specified indentation.
  • Error Handling: The tryexcept block ensures that the program gracefully handles invalid JSON inputs by catching JSONDecodeError.

Steps to Run the Program

  1. Ensure Python is installed on your system.
  2. Copy the code into a file named format_json.py.
  3. Open a terminal or command prompt and navigate to the directory containing the file.
  4. Run the script using the command: python format_json.py.
  5. View the formatted JSON output in the terminal.
© 2024 Learn Programming. All Rights Reserved.

 

5 Replies to “JSON Formatter Program in Python”

Leave a Reply to CraigOxide Cancel reply

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