Convert CSV to JSON using Python

To convert a CSV file to a JSON file using Python:

import pandas as pd

df = pd.read_csv(r"Path where the CSV file is saved\File Name.csv")

df.to_json(r"Path where the new JSON file will be stored\New File Name.json")

Steps to Convert CSV to JSON using Python

Step 1: Prepare the CSV File

To start, prepare a CSV file that you’d like to convert to a JSON file.

For example, let’s prepare a CSV file (called ‘Products‘) that contains the following information:

ProductPrice
Desktop Computer700
Tablet250
Printer120
Laptop1200

Step 2: Install the Pandas Package

If you haven’t already done so, install the Pandas package using this command:

pip install pandas

Step 3: Convert the CSV to JSON using Python

Use the following template to convert the CSV file to a JSON file:

import pandas as pd

df = pd.read_csv(r"Path where the CSV file is saved\File Name.csv")

df.to_json(r"Path where the new JSON file will be stored\New File Name.json")

For example, let’s assume that the path where the ‘Products‘ CSV file is currently stored is:

C:\Users\Ron\Desktop\Test\Products.csv

And the path where the new JSON file (to be called ‘New_Products‘) will be stored:

C:\Users\Ron\Desktop\Test\New_Products.json

You’ll need to modify the paths to reflect the location where the files will be stored on your computer.

Here is the complete Python code to convert the CSV file to a JSON file for our example:

import pandas as pd

df = pd.read_csv(r"C:\Users\Ron\Desktop\Test\Products.csv")

df.to_json(r"C:\Users\Ron\Desktop\Test\New_Products.json")

Run the code in Python (adjusted to your paths), and the new JSON file will be created at your specified location:

If you open the JSON file, you’ll see the following output:

{"Product":{"0":"Desktop Computer","1":"Tablet","2":"Printer","3":"Laptop"},"Price":{"0":700,"1":250,"2":120,"3":1200}}

Formatted result:

{
"Product": {
"0": "Desktop Computer",
"1": "Tablet",
"2": "Printer",
"3": "Laptop"
},
"Price": {
"0": 700,
"1": 250,
"2": 120,
"3": 1200
}
}

You may also want to check the following guides that explain how to convert:

Leave a Comment