JSON and CSV Handling in Python
In this lesson: Handle JSON and CSV in Python with json and csv modules — load, dump, Dict.
JSON and CSV in one minute
| JSON | CSV | |
|---|---|---|
| Looks like | {"name": "Asha", "marks": [91, 88]} | name,marks |
| Best for | Nested data, APIs, config files | Tables: Excel, Google Sheets, reports |
| Python module | json | csv |
| Python type you get | dict / list | list of rows or dicts |
Both modules are built into Python – nothing to install. Almost every real project reads one of these formats: API responses are JSON, school and sales reports are CSV.
JSON strings: dumps() and loads()
import json
student = {"name": "Asha", "class": 12, "subjects": ["Maths", "IP"], "fees_paid": True, "rank": None}
text = json.dumps(student) # Python → JSON text
print(text)
print(type(text).__name__)
back = json.loads(text) # JSON text → Python
print(back["subjects"][1], type(back).__name__)| Python | JSON |
|---|---|
| dict | object {} |
| list, tuple | array [] |
| str | string (double quotes only) |
| int, float | number |
| True / False | true / false |
| None | null |
JSON files: dump() and load()
import json
settings = {"school": "Alpine Public School", "city": "खुर्जा", "session": "2026-27", "sections": ["A", "B"]}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False) # readable + Hindi kept as is
print(open("settings.json", encoding="utf-8").read())
with open("settings.json", encoding="utf-8") as f:
data = json.load(f)
print(data["city"], len(data["sections"]))dumps/loads work with strings; dump/load work with files. Use ensure_ascii=False so Hindi is saved as Hindi, not as \u0916….
Handling bad JSON safely
import json
samples = ['{"ok": true}', "{'ok': True}", '{"ok": true,}']
for s in samples:
try:
print("valid :", json.loads(s))
except json.JSONDecodeError as e:
print("invalid:", s, "→", e.msg)Single quotes, Python’s True and trailing commas are not valid JSON. Always wrap json.loads on outside data in try/except.
Reading CSV with csv.DictReader
import csv
with open("marks.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f)) # each row becomes a dict
print(rows[0])
for r in rows:
total = int(r["maths"]) + int(r["science"]) + int(r["english"])
print(f"{r['name']:<8} total={total:<4} avg={total / 3:.1f}")- CSV values are always strings – convert with
int()/float()before maths. - The csv module handles commas inside quotes (
"Singh, Kabir") correctly;line.split(",")would break. - Open with
newline=""as the Python docs recommend.
Writing CSV with csv.DictWriter
import csv
result = [
{"name": "Asha", "total": 258, "grade": "A"},
{"name": "Ravi", "total": 192, "grade": "B"},
{"name": "Singh, Kabir", "total": 131, "grade": "C"},
]
# utf-8-sig adds a BOM so Excel opens Hindi/₹ correctly
with open("result.csv", "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["name", "total", "grade"])
writer.writeheader()
writer.writerows(result)
print(open("result.csv", encoding="utf-8-sig").read())Save CSV with encoding="utf-8-sig". The invisible BOM tells Excel the file is UTF-8.
Real example: CSV → JSON for a web app
import csv, json
with open("products.csv", newline="", encoding="utf-8") as f:
products = [
{"id": int(r["id"]), "name": r["name"], "price": float(r["price"]), "in_stock": r["stock"] != "0"}
for r in csv.DictReader(f)
]
with open("products.json", "w", encoding="utf-8") as f:
json.dump(products, f, indent=2, ensure_ascii=False)
print(open("products.json", encoding="utf-8").read())This is how a shop owner’s Excel price list becomes data for a website or mobile app.
Common mistakes
| Mistake | Fix |
|---|---|
| Blank lines between rows on Windows | Open CSV with newline="" |
TypeError: Object of type datetime is not JSON serializable | Convert first: d.isoformat(), or json.dumps(x, default=str) |
| Adding numbers from CSV gives “9188” | Convert strings with int() |
| UnicodeDecodeError while reading | Pass encoding="utf-8" (or "utf-8-sig" for Excel files) |
Practice tasks
- Save a list of 5 contacts (name, phone, city) as
contacts.jsonwith indent 2 and load it back. - Read
marks.csv, add apercentagecolumn and writemarks_with_percent.csv. - Convert a JSON list of orders into a CSV that opens correctly in Excel with Hindi names.
- Write a function
safe_load(path)that returns an empty dict if the JSON file is missing or invalid.
Summary
json.dumps/loadsfor strings,json.dump/loadfor files; useindentandensure_ascii=False.- Use
csv.DictReader/DictWriter, open withnewline="", convert values from strings. - Use
utf-8-sigfor Excel-friendly CSV. - Catch
json.JSONDecodeErrorfor outside data.
