Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)