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
try–exceptblock ensures that the program gracefully handles invalid JSON inputs by catchingJSONDecodeError.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
format_json.py. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python format_json.py. - View the formatted JSON output in the terminal.


You are not right. I am assured. I can defend the position. Write to me in PM, we will discuss.
——
https://doodleordie.com/profile/findycarltbrownfycom
I — the same opinion.
——
https://hosting.estate/tags/%D0%B8%D0%BD%D1%81%D1%82%D1%80%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D0%B4%D0%BB%D1%8F%20smm/
Willingly I accept. The theme is interesting, I will take part in discussion.
——
https://the.hosting/bg/help/pljusove-i-minusi-na-distribucijata-whonix
https://uscheapshoeclub.com/findycarcom
виртуальный номер для ватсап