Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
Python code
27 linesimport 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
[
{
"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
- Use `csv.reader` with explicit headers to save memory on huge files.
- 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
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert Image to ASCII Art in Python medium
- Create a Personal Knowledge Base That Searches Notes Instantly in Python easy
Keep learning
Related tutorials and quizzes for this topic.