0
0
PythonHow-ToBeginner · 2 min read

Python How to Convert CSV to JSON Easily

Use Python's csv.DictReader to read the CSV file and json.dump() to write it as JSON, like this: import csv, json; data = list(csv.DictReader(open('file.csv'))); json.dump(data, open('file.json', 'w')).
📋

Examples

Inputname,age Alice,30 Bob,25
Output[{"name": "Alice", "age": "30"}, {"name": "Bob", "age": "25"}]
Inputproduct,price,stock Pen,1.5,100 Notebook,3.0,50
Output[{"product": "Pen", "price": "1.5", "stock": "100"}, {"product": "Notebook", "price": "3.0", "stock": "50"}]
Input
Output[]
🧠

How to Think About It

To convert CSV to JSON, first read the CSV file row by row, treating each row as a dictionary with column headers as keys. Then collect all these dictionaries into a list and write this list to a JSON file or string.
📐

Algorithm

1
Open the CSV file for reading.
2
Use a CSV reader that maps each row to a dictionary using the header row.
3
Collect all row dictionaries into a list.
4
Open a JSON file for writing.
5
Write the list of dictionaries to the JSON file using a JSON writer.
💻

Code

python
import csv
import json

with open('input.csv', 'r', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    rows = list(reader)

with open('output.json', 'w') as jsonfile:
    json.dump(rows, jsonfile, indent=4)

print(json.dumps(rows, indent=4))
Output
[ { "name": "Alice", "age": "30" }, { "name": "Bob", "age": "25" } ]
🔍

Dry Run

Let's trace converting a CSV with two rows to JSON.

1

Read CSV rows

CSV rows read as dictionaries: [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]

2

Convert to JSON

List of dictionaries converted to JSON string with indentation.

Row NumberDictionary
1{"name": "Alice", "age": "30"}
2{"name": "Bob", "age": "25"}
💡

Why This Works

Step 1: Reading CSV as dictionaries

Using csv.DictReader reads each CSV row as a dictionary with keys from the header row, making data easy to work with.

Step 2: Collecting rows

All row dictionaries are collected into a list to represent the entire CSV content.

Step 3: Writing JSON

The list is written to a JSON file using json.dump(), which converts Python objects to JSON format.

🔄

Alternative Approaches

Using pandas library
python
import pandas as pd

df = pd.read_csv('input.csv')
df.to_json('output.json', orient='records', indent=4)
print(df.to_json(orient='records', indent=4))
Pandas is powerful for large or complex CSV files but adds an external dependency.
Manual parsing without csv module
python
with open('input.csv') as f:
    lines = f.read().splitlines()
headers = lines[0].split(',')
data = [dict(zip(headers, line.split(','))) for line in lines[1:]]
import json
print(json.dumps(data, indent=4))
This works for simple CSVs but lacks handling of quoted fields or commas inside values.

Complexity: O(n) time, O(n) space

Time Complexity

Reading each row once makes the time complexity linear, O(n), where n is the number of rows.

Space Complexity

Storing all rows in a list uses O(n) space proportional to the number of rows.

Which Approach is Fastest?

Using csv.DictReader with json.dump() is efficient and simple; pandas is faster for large files but heavier to load.

ApproachTimeSpaceBest For
csv.DictReader + json.dumpO(n)O(n)Simple and medium CSV files
pandas read_csv + to_jsonO(n)O(n)Large or complex CSV files
Manual parsingO(n)O(n)Very simple CSVs, no dependencies
💡
Always use csv.DictReader to easily map CSV rows to dictionaries for JSON conversion.
⚠️
Forgetting to handle the CSV header row properly, which causes incorrect JSON keys.