Back to all snippets
Library/Python/CSV to JSON Conversion
pythonbeginnercsvjsondata-conversionio

How to implement CSV to JSON Conversion in Python

Convert CSV files to JSON format with Python

Quick Answer

`csv.DictReader` parses CSV rows as dicts; collect them in a list and `json.dump()` to write JSON — handles headers automatically.

Code Snippet

1import csv
2import json
3from typing import List, Dict, Any
4
5# CSV to JSON
6def csv_to_json(csv_file: str, json_file: str) -> None:
7    rows = []
8    with open(csv_file, 'r', encoding='utf-8') as f:
9        reader = csv.DictReader(f)
10        for row in reader:
11            rows.append(row)
12    
13    with open(json_file, 'w') as f:
14        json.dump(rows, f, indent=2)
15
16csv_to_json('data.csv', 'data.json')
17
18# JSON to CSV
19def json_to_csv(json_file: str, csv_file: str) -> None:
20    with open(json_file, 'r') as f:
21        data = json.load(f)
22    
23    if not data:
24        return
25    
26    keys = data[0].keys()
27    with open(csv_file, 'w', newline='') as f:
28        writer = csv.DictWriter(f, fieldnames=keys)
29        writer.writeheader()
30        writer.writerows(data)
31
32json_to_csv('data.json', 'output.csv')
33
34# With data transformation
35def csv_to_json_transform(csv_file: str) -> List[Dict[str, Any]]:
36    rows = []
37    with open(csv_file, 'r', encoding='utf-8') as f:
38        reader = csv.DictReader(f)
39        for row in reader:
40            transformed = {
41                'id': int(row['id']),
42                'name': row['name'].title(),
43                'email': row['email'].lower(),
44            }
45            rows.append(transformed)
46    return rows

What is CSV to JSON Conversion?

CSV and JSON are two of the most common data formats. Converting between them is a frequent task. Python makes it trivial with the built-in `csv` and `json` modules — `csv.DictReader` automatically maps column headers to keys.

How It Works

  1. 1Open the CSV file with `with open(file, 'r')`
  2. 2`csv.DictReader(file)` reads rows as dicts with keys from the header row
  3. 3Collect rows in a list
  4. 4`json.dump(data, f)` writes the list to a JSON file

Common Use Cases

  • Data migration - Convert CSV exports to JSON for API bulk import
  • Data analysis - Transform data for loading into databases
  • Format conversion - Export spreadsheet data as JSON
  • Web APIs - Serve CSV data as JSON from a Flask/FastAPI endpoint

Key Benefits

  • No external dependencies — `csv` and `json` are built-in
  • Handles headers automatically with DictReader
  • Readable and maintainable code
  • Works with any CSV structure

Common Mistakes to Avoid

  • Using `csv.reader()` instead of `csv.DictReader()` — reader returns lists, DictReader returns dicts. Use DictReader for easier JSON conversion.
  • Not specifying encoding — some CSVs are UTF-8 with BOM or latin-1. Use `encoding='utf-8-sig'` or `encoding='latin-1'`.
  • Not handling quotes in CSV fields — csv module handles this automatically, but watch for edge cases.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

How do I convert JSON to CSV?

Reverse the process: load JSON, use `csv.DictWriter` to write dicts as rows. Extract field names from the first dict's keys.

How do I handle CSVs with special characters?

Always specify `encoding='utf-8'` or `encoding='utf-8-sig'` (for BOM). If a specific encoding is known, use that instead.

About This Python Code Snippet

This free python code snippet for csv to json conversion is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement csv to json conversion quickly and correctly.

All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.

Tags: csv, json, data-conversion, io  | Language: python  | Difficulty: beginner  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.