Convert CSV to JSON using Python
2 min readSep 9, 2024
import csv
import json
def csv_to_json(csv_file, json_file):
with open(csv_file, mode='r') as file:
csv_reader = csv.DictReader(file)
data = [row for row in csv_reader]
with open(json_file, mode='w') as file:
json.dump(data, file, indent=4)
print(f"CSV to JSON conversion completed! {json_file}")
csv_to_json('Instagram.csv', 'data.json')
#source code --> clcoding.com
CSV to JSON conversion completed! data.json
Here’s an explanation of the code:
1. Imports
import csv
import json
csv
: This module is used to read and write CSV files (Comma Separated Values).json
: This module is used to work with JSON (JavaScript Object Notation) files in Python.
2. Function Definition
def csv_to_json(csv_file, json_file):
This function csv_to_json
is designed to convert a CSV file into a JSON file. It takes two parameters:
csv_file
: The name/path of the CSV file to be read.json_file
: The name/path of the output JSON file to be written.
3. Opening the CSV File
with open(csv_file, mode='r') as file:
csv_reader =…