Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Convert CSV Files to JSON in Python

Convert a CSV file to a JSON file using Python's built-in csv and json modules.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Python code

27 lines
Python 3.9+
import csv
import json

def csv_to_json(csv_filepath, json_filepath):
    """Convert a CSV file to a JSON file."""
    with open(csv_filepath, mode='r', newline='') as csv_file:
        reader = csv.DictReader(csv_file)
        data = [row for row in reader]

    with open(json_filepath, mode='w') as json_file:
        json.dump(data, json_file, indent=2)

if __name__ == "__main__":
    # Example usage
    sample_csv = "sample.csv"
    sample_json = "sample.json"
    # Create a sample CSV file for demonstration
    with open(sample_csv, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
        writer.writeheader()
        writer.writerow({"name": "Alice", "age": "30", "city": "New York"})
        writer.writerow({"name": "Bob", "age": "25", "city": "London"})

    csv_to_json(sample_csv, sample_json)
    # Read and display the resulting JSON
    with open(sample_json, 'r') as f:
        print(f.read())

Output

stdout
[
  {
    "name": "Alice",
    "age": "30",
    "city": "New York"
  },
  {
    "name": "Bob",
    "age": "25",
    "city": "London"
  }
]

How it works

The csv.DictReader reads each row of the CSV as an OrderedDict with the header row as keys, then the list comprehension collects them into a list of dictionaries. That list is written to a JSON file with json.dump, using indent=2 for pretty formatting. The newline='' parameter avoids issues with extra blank lines on Windows.

Common mistakes

  • Forgetting `newline=''` when opening the CSV file may cause stray blank lines.
  • Assuming CSV values are typed — they remain strings unless converted explicitly.

Variations

  1. Use `csv.reader` with explicit headers to save memory on huge files.
  2. Convert specific columns to integers or dates before writing JSON.

Real-world use cases

  • Migrating customer records from a legacy CSV export to a JSON-based API.
  • Ingesting CSV data into a database by first converting to JSON for schema validation.
  • Preparing CSV datasets for web frontends or dashboards that consume JSON.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.