Python How to Convert CSV to JSON Easily
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
How to Think About It
Algorithm
Code
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))
Dry Run
Let's trace converting a CSV with two rows to JSON.
Read CSV rows
CSV rows read as dictionaries: [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]
Convert to JSON
List of dictionaries converted to JSON string with indentation.
| Row Number | Dictionary |
|---|---|
| 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
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))
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))
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| csv.DictReader + json.dump | O(n) | O(n) | Simple and medium CSV files |
| pandas read_csv + to_json | O(n) | O(n) | Large or complex CSV files |
| Manual parsing | O(n) | O(n) | Very simple CSVs, no dependencies |
csv.DictReader to easily map CSV rows to dictionaries for JSON conversion.