Convert CSV to JSON
Parse a CSV file and convert it to a JSON array of objects.
Code
Python
import csv
import json
rows = []
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
rows.append(row)
with open("output.json", "w", encoding="utf-8") as out:
json.dump(rows, out, indent=2)Line-by-line explanation
- 1.Import csv and json modules.
- 2.Use csv.DictReader to read each row as a dictionary.
- 3.Append each row to a list.
- 4.Write the list to a JSON file with json.dump().
Expected output
[{"name": "John", "age": "30"}, {"name": "Jane", "age": "25"}]