How to Convert CSV to JSON in Python – With Code Examples

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.

Try it directly in your browser:

Convert CSV to JSON →

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:

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

Handling messy real-world CSVs

Clean CSVs are rare. A few issues come up again and again. Duplicate or blank header names break DictReader because dictionary keys must be unique — normalize the header row first, giving blank columns explicit names. Inconsistent columns per row (a row with fewer fields than the header) leaves missing keys set to None, which serializes to null; decide whether that's acceptable or should be an error. Byte-order marks from Excel exports sneak an invisible character onto your first header name, so open files with encoding='utf-8-sig' to strip it. And embedded commas or newlines inside quoted fields are handled correctly by the csv module but will corrupt any naive line.split(',') approach — which is exactly why using the standard library parser matters.

Nested JSON from flat CSV

CSV is flat and JSON is hierarchical, so a common need is turning dotted column names like address.city into nested objects. There's no built-in for this, but it's a short loop: split each key on . and walk into nested dictionaries, creating them as you go. Decide up front how to handle types, too — every CSV value arrives as a string, so numeric and boolean fields need explicit conversion (covered in the section above) if the consumer expects real numbers rather than "42". For a one-off job where you don't want to write and debug this logic, the browser-based converter below handles quoting and type inference for you.

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.

Ready to convert csv to json?

Open CSV to JSON Converter →
About the author

Pasindu Ishan is a software developer based in Sri Lanka. He builds developer tools at JSON Dev Tools.