Open In App

Convert CSV to JSON using Python

Last Updated : 21 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 in Python. Every record (or row) is saved as a separate dictionary, with the column names as Keys of the dictionary. All of 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

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

Converting CSV to JSON

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:

Python3




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 '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:

 

 



Previous Article
Next Article

Similar Reads

Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Saving scraped items to JSON and CSV file using Scrapy
In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link http://quotes.toscrape.com/tag/friendship/. This website is provided by the makers of Scrapy, for l
5 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read