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.
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 rowsCSV 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.
Reverse the process: load JSON, use `csv.DictWriter` to write dicts as rows. Extract field names from the first dict's keys.
Always specify `encoding='utf-8'` or `encoding='utf-8-sig'` (for BOM). If a specific encoding is known, use that instead.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.