You may use the following template in order to convert CSV to a JSON string 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')
Next, you’ll see the steps to apply the above template in practice.
Steps to Convert CSV to JSON String using Python
Step 1: Prepare the CSV File
Prepare the CSV file that you’d like to convert to a JSON string.
For example, let’s prepare a CSV file (called ‘Products‘) that contains the following information:
Product | Price |
Desktop Computer | 700 |
Tablet | 250 |
Printer | 120 |
Laptop | 1200 |
Step 2: Install the Pandas Package
If you haven’t already done so, install the Pandas package. You may use the following syntax to install the Pandas package under Windows:
pip install pandas
Step 3: Convert the CSV to JSON String using Python
You may now use the following template to assist you in the conversion of the CSV file to a JSON string:
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:
- The path where the CSV file is saved is: C:\Users\Ron\Desktop\Test\Products.csv
- Where ‘Products‘ is the file name, and ‘csv‘ is the file extension
- The path where the new JSON file will be stored is: C:\Users\Ron\Desktop\Test\New_Products.json
- Where ‘New_Products‘ is the new file name, and ‘json‘ is the file extension
You’ll need to modify the paths to the location where the files will be stored on your computer.
Here is the complete Python code to convert the CSV file to the JSON string 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 string:
{"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: