Python Code to Convert CSV into JSON

Convert CSV into JSON using Python code. Before we start our actual problem, lets understand JSON and CSV little bit.

JSON stands for JavaScript Object Notation, a text-based file format used to transfer data between the applications. It is one of the methods most data travel on the internet using API. CSV file is also one of the most useful resources for the same.

Convert CSV into JSON

In today’s tutorial, we are going to convert a CSV file into JSON file using Python dictionary. So for this sample program, we used a sample data file sample.CSV file.

News website using Django and JSON data (API)

as you are well aware that a CSV file is a comma-separated text file, The first row of CSV file contains the headers of the rest of the lines contains the data.

For this program, we have used a sample CSV file named SampleData and opened in reading mode. All the text files can be read directly but CSV files are little bit different.

import csv

This is a special module in Python that is designed to read or write CSV file. Here is a source code for converting the CSV file into JSON format.

import csv
import json

data = []
keys = []
with open("E:/python/Tools/SampleData.csv") as csv_file:
    csv_data = csv.reader(csv_file)
    count = 1
    for row in csv_data:
        if count == 1:
            for y in row:
                keys.append(y)
        else:
            element = {}
            for y in range(len(row)):
                element[keys[y]] = row[y]
            data.append(element)
        count = count+1

print(json.dumps(data,))

From the above code, you can see that we have first of all stored all the header in a list named Keys[] using the following code.

if count == 1:
     for y in row:
         keys.append(y)

and all the other rows in another dictionary variable element. and finally, this element is appended in a list of data.

whenever you will print this list of dictionary element this seems to be a perfect JSON format but it is not. Since all the data in JSON format need every key and value must be in double inverted quotation marks.

print(json.dumps(data,))

Thus used the JSON module for convert into native JSON format using json.dumps() module.

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.