Reading CSV & JSON
Overview
Read and write structured CSV spreadsheets and JSON config files using standard Python libraries.
Learning Objectives
- Read CSV files using DictReader to map column cells.
- Serialize and deserialize JSON configs.
- Handle numeric conversions and formats safely.
Concept Explanation
Python's csv module parses tabular files safely, handling commas and quotes inside fields. csv.DictReader loads rows as dictionaries. The json module translates text to dictionary objects using json.loads (for strings) and json.load (for files).
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
import csv, json
# Standard modules for parsing files
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
import csv
raw_csv = 'name,role\nAlice,admin\nBob,user'
reader = csv.DictReader(raw_csv.splitlines())
for row in reader:
print(row['name'], 'is', row['role'])
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
import json
def format_payload(json_string):
try:
# Convert JSON string to dictionary
data = json.loads(json_string)
# Convert dictionary back to formatted JSON text
return json.dumps(data, indent=4)
except json.JSONDecodeError as e:
print('Invalid JSON syntax:', e)
return None
print(format_payload('{"status": "ok", "code": 200}'))
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Open text stream → Tokenize symbols → Construct key-value dictionaries → Return parsed collections
Common Mistakes
Review these common pitfalls when working with this topic:
- Forgetting to typecast parsed CSV numbers before doing math (CSV cell values are always strings).
- Using regular expressions to parse JSON strings instead of the json module.
- Calling json.load() on string variables instead of using json.loads().
- Trying to serialize custom class objects without custom JSONEncoders.
Best Practices
Enforce these Pythonic best practices in your codebase:
for line in f:
cells = line.split(',') # Fails if values contain quotes or commas
import csv
reader = csv.reader(f) # Safely parses CSV structures and quotes
Quick Revision
Use these key summaries for last-minute revision:
- csv module handles tabular comma-separated values.
- DictReader reads rows as dictionaries.
- json.loads() parses JSON string values.
- json.dumps() converts dictionaries to JSON strings.
- Specify indent inside dumps() for pretty printing.
- Cast numeric fields explicitly after parsing.