Python JSON Convert CSV to JSON using Python

Python JSON Convert CSV to JSON using Python

Convert CSV to JSON using Python

We will create a JSON file that will have several dictionaries, each representing a record (row) from the CSV file, with the Key as the column specified. 

Sample CSV File used: 

First step: you need to create emp_details.csv file before converting to emp_details.Json file

Second step: you need to specify the path of the csv file in the Python program

Third step:convert each row to dictionary

Fourth step: assume emp_name as the primary key

Python program to convert CSV  file to JSON file:

import csv 
import json

# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):

# create a dictionary
data = {}

# Open a csv reader called DictReader
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)

# Convert each row into a dictionary
# and add it to data
for rows in csvReader:

# Assuming a column named 'emp_name' to
# be the primary key
key = rows['emp_name']
data[key] = rows

# Open a json writer, and use the json.dumps()
# function to dump data
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonf.write(json.dumps(data, indent=4))

# Driver Code

# Decide the two file paths according to your
# computer system
csvFilePath = r'emp_details.csv'
jsonFilePath = r'emp_details.json'

# Call the make_json function
make_json(csvFilePath, jsonFilePath)



So the above python porgram converts csv file to json file