How to convert csv to json in python – How to Convert CSV to JSON Array in Python?

What do you mean by CSV File?

How to convert csv to json in python: A CSV file, which stands for Comma Separated Values file, is a simple text file that maintains a list of data. CSV files are commonly used to exchange data between different applications. Contact Managers and Databases, for example, typically support CSV files.

These CSV files are also known as Comma Separated Values or Comma Delimited Files. These files primarily use the comma character to delimit or segregate data. However, other characters, such as semicolons, are sometimes used. The plan is to export complex data from one program to a CSV file and then import the data from the CSV file into another program.

A Comma Separated Values (CSV) file has a simple structure that contains some data that is listed and separated by commas. CSV files are constructed in such a way that they may simply import and export data from other applications. The resulting data is easily readable by humans and may be seen using a text editor like Notepad or a spreadsheet program like Microsoft Excel or Google Sheets.

What do you mean by JSON Array?

Convert csv to json python: JSON (JavaScript Object Notation) is a dictionary-like notation that may be utilized in Python by importing the JSON module. Every record (or row) is preserved as its own dictionary, with the column names serving as the dictionary’s Keys. To make up the whole dataset, all of these records are kept as dictionaries in a nested dictionary. It is saved together with the extension. geeksforgeeks.json

JSON format was actually based on a subset of JavaScript. It is, nevertheless, referred to as a language-independent format, and it is supported by a wide range of programming APIs. In most cases, JSON is used in Ajax Web Application Programming. Over the last few years, the popularity of JSON as an alternative to XML has gradually increased.

While many programs use JSON for data transfer, they may not keep JSON format files on their hard drive. Data is exchanged between computers that are linked via the Internet.

Convert CSV to JSON Array in Python

Python convert csv to json: Let us consider the below CSV file as an example:

ID NAME SALARY
1 Dhoni 100000
2 Virat 90000
3 Sheela 25000
4 John 40000
5 Kevin 20000
6 Mary 30000
7 Rohit 70000
8 Sindhu 60000
9 Hardik 50000

Now we create an empty JSON file say samplejsonfile.json.

Here, we convert the above given CSV file data into JSON array and store it in samplejsonfile.json

Approach:

  • Import csv module using the import keyword.
  • Import json module using the import keyword.
  • Take some random CSV file and store it in a variable
  • Take an empty JSON file and store it in another variable
  • Create a new empty dictionary
  • Open the given csv file using open() function
  • Pass the given csv file as an argument to the DictReader() function of the csv module to Convert the given csv file data into a dictionary.
  • Store it in a variable
  • Loop in the rows of the above csv file data using the for loop
  • Print the row data for reference
  • Append all the row data to the above-created json dictionary.
  • Open the given json file in write mode using the open() function
  • Pass the above json dictionary, indent as arguments to the dumps() function of the json module to dump all the data into gvn_jsonfile(samplejsonfile.json)
  • Here indent is used for elegant printing.
  • The Exit of the Program.

Below is the implementation:

# Import csv module using the import keyword.
import csv  
# Import json module using the import keyword.
import json  
# Take some random CSV file and store it in a variable
gvn_csvfile = 'demo.csv'  
# Take an empty JSON file and store it in another variable
gvn_jsonfile = 'samplejsonfile.json'  

# Create a new empty dictionary
json_dictionary = {}  

# Open the given csv file using open() function 
with open(gvn_csvfile) as gvn_csvfile:
  # Pass the given csv file as an argument to the DictReader() function of the csv module
  # to Convert the given csv file data into dictionary
  # Store it in a variable
  csvfiledata = csv.DictReader(gvn_csvfile)

  json_dictionary["data"]=[]
  # Loop in the rows of the above csv file data using the for loop
  for row_data in csvfiledata:  
    # Print the row data for reference
    print(row_data)
    # Append all the row data to the above created json dictionary.
    json_dictionary["data"].append(row_data)  

# Open the given json file in write mode using the open() function 
with open(gvn_jsonfile, 'w') as gvn_jsonfile:  
  # Pass the above json dictionary, indent as arguments to the dumps() function 
  # of the json module to dump all the data into gvn_jsonfile(samplejsonfile.json)
  # Here indent is used for elegant printing.
  gvn_jsonfile.write(json.dumps(json_dictionary, indent = 4))  

Output:

OrderedDict([('ID', '1'), ('NAME', 'Dhoni'), ('SALARY', '100000')])
OrderedDict([('ID', '2'), ('NAME', 'Virat'), ('SALARY', '90000')])
OrderedDict([('ID', '3'), ('NAME', 'Sheela'), ('SALARY', '25000')])
OrderedDict([('ID', '4'), ('NAME', 'John'), ('SALARY', '40000')])
OrderedDict([('ID', '5'), ('NAME', 'Kevin'), ('SALARY', '20000')])
OrderedDict([('ID', '6'), ('NAME', 'Mary'), ('SALARY', '30000')])
OrderedDict([('ID', '7'), ('NAME', 'Rohit'), ('SALARY', '70000')])
OrderedDict([('ID', '8'), ('NAME', 'Sindhu'), ('SALARY', '60000')])
OrderedDict([('ID', '9'), ('NAME', 'Hardik'), ('SALARY', '50000')])

Now the data from the demo.csv file is dumped into the samplejsonfile.json file

samplejsonfile.json:

{
    “data”: [
        {
            “ID”: “1”,
            “NAME”: “Dhoni”,
            “SALARY”: “100000”
        },
        {
            “ID”: “2”,
            “NAME”: “Virat”,
            “SALARY”: “90000”
        },
        {
            “ID”: “3”,
            “NAME”: “Sheela”,
            “SALARY”: “25000”
        },
        {
            “ID”: “4”,
            “NAME”: “John”,
            “SALARY”: “40000”
        },
        {
            “ID”: “5”,
            “NAME”: “Kevin”,
            “SALARY”: “20000”
        },
        {
            “ID”: “6”,
            “NAME”: “Mary”,
            “SALARY”: “30000”
        },
        {
            “ID”: “7”,
            “NAME”: “Rohit”,
            “SALARY”: “70000”
        },
        {
            “ID”: “8”,
            “NAME”: “Sindhu”,
            “SALARY”: “60000”
        },
        {
            “ID”: “9”,
            “NAME”: “Hardik”,
            “SALARY”: “50000”
        }
    ]
}