ETL in Python: Extract CSV, Transform Dict, Load JSON
Build a simple ETL pipeline in Python that reads a CSV file, transforms each row (stripping whitespace and converting numeric fields), and writes the result to JSON.
Python code
42 linesimport csv
import json
from pathlib import Path
def extract_csv(file_path):
"""Read CSV file and return list of row dictionaries."""
with Path(file_path).open('r', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
return list(reader)
def transform_dicts(rows):
"""Transform row dicts: strip whitespace and convert numeric fields."""
for row in rows:
for key, value in list(row.items()):
if value is not None:
row[key] = value.strip()
if 'age' in row:
row['age'] = int(row['age']) if row['age'].isdigit() else row['age']
if 'salary' in row:
row['salary'] = float(row['salary'])
return rows
def load_json(data, output_path):
"""Write list of dicts to JSON file with indentation."""
with Path(output_path).open('w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
return output_path
if __name__ == "__main__":
csv_file = "data.csv" # sample: name,age,salary,city
json_file = "output.json"
# Create sample CSV for demonstration
sample_csv = "name,age,salary,city\nAlice,30,75000.50,NYC\nBob,25,52000.00,LA\n"
Path(csv_file).write_text(sample_csv, encoding='utf-8')
extracted = extract_csv(csv_file)
transformed = transform_dicts(extracted)
load_json(transformed, json_file)
print(f"Transformed {len(transformed)} records to {json_file}")
print(json.dumps(transformed, indent=2))
Output
Transformed 2 records to output.json
[
{
"name": "Alice",
"age": 30,
"salary": 75000.5,
"city": "NYC"
},
{
"name": "Bob",
"age": 25,
"salary": 52000.0,
"city": "LA"
}
]
How it works
The pipeline uses three focused functions: extract_csv reads the CSV with csv.DictReader into a list of dictionaries. transform_dicts iterates over each row, strips whitespace from string values, and converts numeric-looking fields to int or float based on presence. load_json writes the final list to a file with json.dump and indent=2 for readability. The if __name__ == "__main__" block keeps the script executable while allowing functions to be imported elsewhere.
Common mistakes
- Forgetting to convert numeric strings, leaving them as text in the JSON output.
- Opening CSV without `newline=''`, which can cause extra blank lines on Windows.
- Not handling missing or non-numeric 'age' values — using `isdigit()` only catches integers, not decimals.
Variations
- Use a dict comprehension with a type-check function to transform fields in one pass.
- Use `pandas.read_csv` and `df.to_json` for larger datasets (requires pandas).
Real-world use cases
- Migrating legacy CSV exports from an ERP system into a data warehouse's JSON ingestion layer.
- Building a nightly job that converts vendor spreadsheets into JSON for an analytics API.
- Preparing CSV logs from a web server into structured JSON for downstream monitoring tools.
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.