Open In App

Convert CSV to JSON using Python

Last Updated : 01 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature variable.

On the other hand, JSON (or JavaScript Object Notation) is a dictionary-like notation that can be used by importing the JSON package into Python.

Refer to the below articles to understand the basics of JSON and CSV.

Converting CSV to JSON in Python

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

Sample CSV File used

Every record (or row) is saved as a separate dictionary, with the column names as Keys of the dictionary. These records as dictionaries are saved in a nested dictionary to compose the entire dataset. It is stored with the extension .json, for example, geeksforgeeks.json

Python
import csv
import json

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 'No' to
            # be the primary key
            key = rows['No']
            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'Names.csv'
jsonFilePath = r'Names.json'

# Call the make_json function
make_json(csvFilePath, jsonFilePath)

Output:

 


Next Article

Similar Reads

three90RightbarBannerImg