Python - Convert CSV to JSON
Python - CSV to JSON
To convert CSV to JSON in Python, follow these steps.
- Initialize a Python List.
- Read the lines of CSV file using csv.DictReader() function.
- Convert each line into a dictionary. Add the dictionary to the Python List created in step 1.
- Convert the Python List to JSON String using json.dumps().
- You may write the JSON String to a JSON file.
The format of CSV input and JSON output would be as shown in the following.
Input - data.csv
column_1,column_2,column_3
value_1_1,value_1_2,value_1_3
value_2_1,value_2_2,value_2_3
value_3_1,value_3_2,value_3_3
Output - data.json
[
{
"column_1": "value_1_1",
"column_2": "value_1_2",
"column_3": "value_1_3"
},
{
"column_1": "value_2_1",
"column_2": "value_2_2",
"column_3": "value_2_3"
},
{
"column_1": "value_3_1",
"column_2": "value_3_2",
"column_3": "value_3_3"
}
]
Examples
1. Convert CSV file to JSON
In this example, we will read the following CSV file and convert it into JSON file.
data.csv - CSV File
a,b,c
25,84,com
41,52,org
58,79,io
93,21,co
Python Program
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)
data.json Output File
[
{
"a": "25",
"b": "84",
"c": "com"
},
{
"a": "41",
"b": "52",
"c": "org"
},
{
"a": "58",
"b": "79",
"c": "io"
},
{
"a": "93",
"b": "21",
"c": "co"
}
]
Summary
In this Python JSON Tutorial, we learned how to convert a CSV file to JSON file using csv and json libraries.