Convert CSV to JSON Using Python – A Beginner’s Guide

Converting CSV File To JSON File Using Python 1 Png

In this article, we will convert CSV to JSON using a simple Python script. We’ll learn how to use the JSON (JavaScript Object Notation) library of Python and will try to understand the logic behind this conversion.

Why would you want to convert CSV to JSON?

JSON is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications, so whenever there’s a need to send some data from the server to the client, the data is first converted to JSON and then sent to the client so it can be displayed on a web page, or vice versa.

Steps Involved in Converting CSV to JSON

We will approach his problem in various small steps so that we understand the problem thoroughly and easily.

Step 1: Take input the CSV file and the JSON file paths

This can be achieved with the help of the input function. Input function by default takes input in the form of a string and this is exactly what we need. Input function can also be used to display some string while asking for input

Step 2: Open the CSV file using a file handler

A file handler can easily be initiated, there are many ways to do this but we will stick to the safest one i.e. we will use:

with open(csv_file_path, encoding = 'utf-8') as csv_file_handler:

This will open the file in reading mode, and as soon as we move out of this block, it’ll automatically close this file. Closing a file after use is very important to prevent the file from corrupting or any chances of data loss.

Step 3: Open the JSON file using JSON file handler

This file will be opened in write mode and thus the code changes to:

with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler:

Here ‘+w’ represents that the file is being opened in write mode, i.e. its data can be changed

Step 4: Parse the file into a JSON file using the functions of the JSON module

This task can easily be accomplished by using the following piece of code:

json_file_handler.write(json.dumps(data_dict, indent = 4))

And you’re all set, now you just need to run the code and your job will be done

Complete Code to Convert CSV to JSON in Python

import csv
import json

def csv_to_json(csv_file_path, json_file_path):
	#create a dictionary
	data_dict = {}

	#Step 2
	#open a csv file handler
	with open(csv_file_path, encoding = 'utf-8') as csv_file_handler:
		csv_reader = csv.DictReader(csv_file_handler)

		#convert each row into a dictionary
		#and add the converted data to the data_variable

		for rows in csv_reader:

			#assuming a column named 'No'
			#to be the primary key
			key = rows['Serial Number']
			data_dict[key] = rows

	#open a json file handler and use json.dumps
	#method to dump the data
	#Step 3
	with open(json_file_path, 'w', encoding = 'utf-8') as json_file_handler:
		#Step 4
		json_file_handler.write(json.dumps(data_dict, indent = 4))

#driver code
#be careful while providing the path of the csv file
#provide the file path relative to your machine

#Step 1
csv_file_path = input('Enter the absolute path of the CSV file: ')
json_file_path = input('Enter the absolute path of the JSON file: ')

csv_to_json(csv_file_path, json_file_path)

Running The Code

Input Csv File
Input Csv File

Command For Running The Script

$ python3 "python script name without quotes"
Running Python Script In Terminal
Running Python Script In Terminal

Output File

Json File Generated As Output
Json File Generated As Output

Conclusion

In this article, we learned how to implement a Python script that can create/convert CSV to JSON. We also learned about the ‘json‘ and ‘csv‘ modules of Python and their common functions.

References

https://medium.com/@hannah15198/convert-csv-to-json-with-python-b8899c722f6d

https://stackoverflow.com/questions/19697846/how-to-convert-csv-file-to-multiline-json