Description:
JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. Python provides built-in support for handling JSON through the `json` module.
Reading a JSON file involves loading the data into a Python dictionary or list for further processing.
Steps:
1. Import the `json` module
2. Open the JSON file
3. Parse JSON data
4. Access and manipulate data
5. Close the file
Step-by-Step Process
Import the json Module: This module contains methods to handle JSON files.
Open the JSON File: Use the `open()` function to open the file in read mode.
Parse JSON Data: Use the `json.load()` method to parse the file's content into a Python object (typically a dictionary or list).
Access and Manipulate Data: Work with the loaded data as a regular Python dictionary or list.
Close the File: Although using `with open()` automatically handles closing, explicitly closing the file is good practice in manual operations.
Sample Source Code
# Code for Reading JSON File in Python
import json
path='/home/soft23/Documents/sample.json'
# Open the JSON file
with open(path, 'r') as file:
# Parse the JSON data
data = json.load(file)
# Access the JSON data
print("Company:", data["company"])
print("Location:", data["location"])
print("\nEmployees:")
for employee in data["employees"]:
print(f"ID: {employee['id']}, Name: {employee['name']}, Department: {employee['department']}")