Converting a CSV file to JSON in Python takes about five lines of code using the standard library. This article covers the built-in csv module approach (no dependencies required), the pandas shortcut, and a few practical patterns for handling numeric types and nested structures.
Method 1 — csv.DictReader (standard library, no install)
Given a CSV file like this:
name,age,city Alice,30,London Bob,25,Paris Carol,35,Berlin
Here is the conversion:
import csv
import json
with open('data.csv', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
rows = list(reader)
print(json.dumps(rows, indent=2))
Output:
[
{
"name": "Alice",
"age": "30",
"city": "London"
},
{
"name": "Bob",
"age": "25",
"city": "Paris"
},
{
"name": "Carol",
"age": "35",
"city": "Berlin"
}
]
Notice that age is a string ("30"), not a number (30). The CSV format has no type information — everything is text. See below for how to fix this.
Writing the JSON to a file
with open('data.csv', newline='', encoding='utf-8') as infile, \
open('output.json', 'w', encoding='utf-8') as outfile:
rows = list(csv.DictReader(infile))
json.dump(rows, outfile, indent=2)
Converting numeric fields from string to number
If you know which columns should be numbers, convert them after reading:
import csv
import json
numeric_columns = {'age'}
with open('data.csv', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
rows = []
for row in reader:
for col in numeric_columns:
try:
row[col] = int(row[col])
except (ValueError, KeyError):
pass
rows.append(row)
print(json.dumps(rows, indent=2))
Now age appears as 30 (a number) instead of "30" (a string).
Method 2 — pandas (two lines)
If you have pandas installed, the conversion is even shorter, and pandas infers numeric types automatically:
import pandas as pd
df = pd.read_csv('data.csv')
print(df.to_json(orient='records', indent=2))
The orient='records' argument produces a JSON array where each row is an object — the most common format for API consumption. Other orient options:
orient='index'— a dict keyed by row indexorient='columns'— a dict keyed by column name (column-oriented)orient='values'— a 2D array without column names
Handling special characters and encoding
Always specify encoding='utf-8' when opening CSV files, especially if they contain non-ASCII characters (accented names, Unicode symbols). For CSV files exported from Excel, you may need encoding='utf-8-sig' to handle the byte-order mark:
with open('data.csv', newline='', encoding='utf-8-sig') as f:
...
Command-line one-liner
For quick terminal use:
python3 -c " import csv, json, sys print(json.dumps(list(csv.DictReader(sys.stdin)), indent=2)) " < data.csv
No-code alternative
If you do not need to script the conversion, the CSV to JSON Converter lets you paste or upload a CSV file and download the JSON output immediately — no Python required.