Sub topic 2
Handling JSON Errors and CSV Tables in Python
Assume you know basic Python syntax, dictionaries, lists, functions, exceptions, and the with statement. This chapter focuses on safely handling input and keeping CSV data usable.
Handling malformed JSON
JSON must follow strict syntax. For example, JSON uses double quotes for strings and does not allow trailing commas. json.loads raises JSONDecodeError when a string is invalid.
import json
text = '{"name": "Ada",}'
try:
user = json.loads(text)
except json.JSONDecodeError as error:
print(f"Invalid JSON at line {error.lineno}, column {error.colno}")
print(error.msg)Catch this exception at the boundary where external data enters your program. Do not silently replace invalid data with an empty dictionary, because that can hide data loss.
Serializing dates and other custom types
JSON supports strings, numbers, booleans, null, arrays, and objects. Python dates, sets, and custom classes are not directly supported. Pass a function through default to convert them.
import json
from datetime import datetime
def encode(value):
if isinstance(value, datetime):
return value.isoformat()
raise TypeError(f"Cannot serialize {type(value).__name__}")
record = {"created_at": datetime(2026, 11, 26, 10, 50)}
print(json.dumps(record, default=encode))The decoder will receive an ISO 8601 timestamp as a string. Convert it back to a datetime explicitly when reading it.
Reading and writing CSV
CSV files contain rows and columns, but the csv module handles quoting and embedded commas for you. Use newline="" and an explicit encoding when opening CSV files.
import csv
rows = [["name", "qty"], ["apple", "3"], ["pear, green", "5"]]
with open("items.csv", "w", newline="", encoding="utf-8") as file:
csv.writer(file).writerows(rows)
with open("items.csv", newline="", encoding="utf-8") as file:
for row in csv.reader(file):
print(row)Named columns with dictionaries
DictReader uses the header row as dictionary keys. CSV values are always strings, so convert them before calculations. DictWriter writes dictionaries when you provide fieldnames.
import csv
with open("items.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
print(row["name"], int(row["qty"]) * 2)
with open("items_out.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "qty"])
writer.writeheader()
writer.writerow({"name": "orange", "qty": 4})Exercise
Why does int(row["qty"]) matter when reading CSV?
Show answer
CSV readers return every field as a string. Converting the value makes numeric arithmetic work correctly.