Skip to main content

Standard Library

JSON & CSV

Complete lesson for JSON & CSV using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — JSON & CSV

Section: Standard Library. Read and write JSON and CSV in Python — programs create their own files, then parse, transform, and save clean data.

JSON vs CSV at a glance

  • JSON stores nested objects and arrays as text — great for APIs and configs.
  • CSV stores rectangular tables as comma-separated rows — great for spreadsheets.
  • Python stdlib: import json and import csv.
  • Lesson programs always create the files they read so they run anywhere.
FormatShapeTypical use
JSONNested objects/arraysAPIs, configs, documents
CSVRows and columnsExports, Excel, reports
Both textUnicode mattersPrefer utf-8 encoding

json.dumps and json.loads

  • dumps serializes a Python object to a JSON string; loads parses a string back.
  • Types: dict→object, list/tuple→array, str→string, int/float→number, True/False/None→true/false/null.
  • indent=2 pretty-prints; sort_keys=True stabilizes key order.
  • Keys in JSON objects must be strings — non-string dict keys are coerced to strings on dump.
import json

data = {"course": "Python", "levels": 6, "active": True, "tutor": None}
text = json.dumps(data, indent=2)
print(text)
print(json.loads(text)["course"])

json.dump and json.load with files

  • dump(obj, file) writes to an open text file; load(file) reads.
  • Always open with encoding='utf-8' on Windows.
  • Create parent content in the same program before reading — do not assume the file exists.
  • Use context managers: with open(path, 'w', encoding='utf-8') as f:.
import json
from pathlib import Path

path = Path("demo_config.json")
payload = {"host": "localhost", "port": 8000}
with path.open("w", encoding="utf-8") as f:
    json.dump(payload, f, indent=2)
with path.open("r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded)

csv.writer basics

  • csv.writer(f) writes rows from lists/tuples.
  • writerow for one row; writerows for many.
  • Open files with newline='' as the csv docs recommend (avoids blank lines on Windows).
  • Create the CSV in the program, then read it back to verify.
import csv
from pathlib import Path

path = Path("demo_scores.csv")
rows = [["name", "score"], ["Asha", "90"], ["Bala", "85"]]
with path.open("w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)
with path.open("r", encoding="utf-8", newline="") as f:
    for row in csv.reader(f):
        print(row)

DictReader and DictWriter

  • DictWriter takes fieldnames and writes dict rows.
  • writeheader() writes the header line once.
  • DictReader yields dicts keyed by the header row.
  • Ideal when columns have stable names.
import csv
from pathlib import Path

path = Path("demo_people.csv")
fields = ["name", "city"]
people = [{"name": "Cara", "city": "Pune"}, {"name": "Dev", "city": "Hyderabad"}]
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=fields)
    w.writeheader()
    w.writerows(people)
with path.open("r", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["city"])

Pretty JSON and compact JSON

  • Pretty: indent=2 for humans and git diffs.
  • Compact: default separators for smaller API payloads.
  • ensure_ascii=False keeps Unicode characters readable (names in Indian languages, etc.).
  • Still create the file before any load demo.
import json
from pathlib import Path

path = Path("demo_unicode.json")
data = {"greeting": "नमस्ते", "ok": True}
with path.open("w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
print(path.read_text(encoding="utf-8"))

CSV dialects and delimiters

  • Default dialect uses comma; TSV uses delimiter='\t'.
  • csv.excel and csv.unix_dialect exist for compatibility.
  • Quote rules matter when fields contain commas or quotes.
  • Prefer DictReader when the first row is a header.
import csv
from pathlib import Path

path = Path("demo_tsv.txt")
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.writer(f, delimiter="\t")
    w.writerow(["id", "label"])
    w.writerow([1, "alpha"])
with path.open("r", encoding="utf-8", newline="") as f:
    for row in csv.reader(f, delimiter="\t"):
        print(row)

Type fidelity limitations

  • JSON has no tuple or set — they become arrays; load gives lists.
  • CSV everything is a string until you cast (int(row['score'])).
  • datetime is not JSON-native — store ISO strings and parse back.
  • Booleans and nulls work in JSON; CSV needs agreed conventions (true/false, empty).
PythonJSONCSV cell
dictobjectN/A (row of cells)
listarrayone column value / multiple cols
Truetrue'True' string unless coded
Nonenulloften empty field
datetimeISO string by conventionISO string by convention

Error handling patterns

  • json.JSONDecodeError on bad JSON text.
  • Missing CSV headers → KeyError on DictReader rows if you assume a key.
  • Always create sample files in demos; catch decode errors in real apps.
  • Validate required keys after load before use.
import json

bad = "{'not': 'json'}"
try:
    json.loads(bad)
except json.JSONDecodeError as exc:
    print("decode failed:", exc.msg)

pathlib and cwd notes

  • Path('file.json') is relative to the process current working directory.
  • Verification runs in a temp folder — relative names are fine when the program creates them there.
  • Path.write_text / read_text are handy for small JSON strings.
  • Do not hardcode machine-specific absolute paths in lesson programs.
L2

Advanced — JSON & CSV

Custom JSON encoding

  • json.dumps fails on unknown types (datetime, set, Decimal) unless you help it.
  • Pass default= callable to convert unknown objects to serializable forms.
  • Subclass json.JSONEncoder for reusable encoders.
  • Store datetimes as ISO strings — never rely on now() inside encoders for lessons.
import json
from datetime import date

def default(o):
    if isinstance(o, date):
        return o.isoformat()
    raise TypeError(f"x cannot serialize {type(o)!r}")

payload = {"day": date(2026, 10, 25), "tags": ["python", "json"]}
print(json.dumps(payload, default=default))

csv quoting and special fields

  • Fields with commas, quotes, or newlines get quoted automatically by the writer.
  • quoting=csv.QUOTE_MINIMAL is default; QUOTE_ALL quotes every field.
  • escapechar interacts with dialects — prefer defaults unless integrating legacy systems.
  • Round-trip write then read in tests to prove quoting.
import csv
from pathlib import Path

path = Path("demo_quoted.csv")
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.writer(f)
    w.writerow(["name", "note"])
    w.writerow(["Ada", "Likes commas, and quotes"])
with path.open("r", encoding="utf-8", newline="") as f:
    print(list(csv.reader(f)))

Large files and streaming

  • Prefer iterative json.load only for whole documents that fit in memory.
  • For huge JSON arrays, consider ijson (third party) — stdlib loads all at once.
  • CSV readers are naturally streaming row-by-row — good for large tables.
  • Write CSV incrementally with writerow in a loop.

UTF-8 BOM and Excel

  • Excel on Windows sometimes expects UTF-8 BOM for CSV.
  • You can write utf-8-sig encoding so Excel opens Unicode correctly.
  • utf-8-sig on read strips a leading BOM if present.
  • For APIs and tools, plain utf-8 without BOM is usually better.
import csv
from pathlib import Path

path = Path("demo_excel.csv")
with path.open("w", encoding="utf-8-sig", newline="") as f:
    w = csv.writer(f)
    w.writerow(["name", "city"])
    w.writerow(["ओम", "Delhi"])
with path.open("r", encoding="utf-8-sig", newline="") as f:
    print(list(csv.reader(f)))

Nested JSON to CSV flattening

  • CSV is flat — nested JSON needs flattening or multiple tables.
  • Common approach: one CSV for parents, one for child arrays with foreign keys.
  • Or stringify nested objects into a JSON cell (hybrid).
  • Document the schema when you flatten.
import csv
import json
from pathlib import Path

users_path = Path("demo_users.json")
csv_path = Path("demo_users_flat.csv")
users = [
    {"id": 1, "name": "Asha", "skills": ["python", "sql"]},
    {"id": 2, "name": "Bala", "skills": ["java"]},
]
users_path.write_text(json.dumps(users), encoding="utf-8")
with csv_path.open("w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["id", "name", "skills"])
    w.writeheader()
    for u in json.loads(users_path.read_text(encoding="utf-8")):
        w.writerow({"id": u["id"], "name": u["name"], "skills": "|".join(u["skills"])})
print(csv_path.read_text(encoding="utf-8"))

Schema validation mindset

  • After load, check required keys and types explicitly.
  • Reject unknown fields or keep them in an extra dict — be consistent.
  • Version your JSON configs (schema_version: 1).
  • For CSV, verify header == expected fieldnames before processing.
import json

def load_course(text):
    data = json.loads(text)
    required = {"title", "levels"}
    missing = required - data.keys()
    if missing:
        raise KeyError(f"missing {missing}")
    if not isinstance(data["levels"], int):
        raise TypeError("levels must be int")
    return data

print(load_course('{"title": "Python", "levels": 6}'))

Atomic writes

  • Write to a temp file in the same directory, then replace into the final name.
  • Avoids torn JSON/CSV if the process crashes mid-write.
  • Path.replace is overwriting rename on Python 3.
  • Still create files inside the program for demos.
import json
from pathlib import Path

final = Path("demo_atomic.json")
tmp = Path("demo_atomic.json.tmp")
data = {"ok": True}
tmp.write_text(json.dumps(data), encoding="utf-8")
tmp.replace(final)
print(final.read_text(encoding="utf-8"))

json lines (JSONL) pattern

  • One JSON object per line — easy to append and stream.
  • Write with json.dumps(obj) + '\n' per record.
  • Read line-by-line with loads, skipping blanks.
  • Not the same as one big JSON array file.
import json
from pathlib import Path

path = Path("demo_events.jsonl")
events = [{"id": 1, "evt": "login"}, {"id": 2, "evt": "logout"}]
with path.open("w", encoding="utf-8") as f:
    for e in events:
        f.write(json.dumps(e) + "\n")
with path.open("r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line:
            print(json.loads(line))
L3

Tricky Interview Points

Q1) dumps vs dump?

Answer dumps returns a JSON string. dump writes JSON to a file object.

Q2) loads vs load?

Answer loads parses a JSON string. load parses from a file object.

Q3) Why open CSV with newline=''?

Answer The csv module handles newlines itself; newline='' avoids extra blank rows on Windows.

Q4) DictReader benefit?

Answer Each row becomes a dict keyed by header names, clearer than numeric indexes.

Q5) How are Python tuples serialized in JSON?

Answer As JSON arrays; loading gives lists, not tuples.

Q6) How do you store datetime in JSON?

Answer Convert to ISO string with .isoformat() and parse back with fromisoformat.

Q7) What exception does bad JSON raise?

Answer json.JSONDecodeError.

Q8) ensure_ascii=False purpose?

Answer Keeps non-ASCII characters as themselves instead of \uXXXX escapes.

Q9) CSV type problem?

Answer All fields are strings; convert with int/float/decimal as needed.

Q10) How to write a header with DictWriter?

Answer Call writeheader() before writerows.

Q11) JSON object key type?

Answer Keys must be strings in JSON. Python dumps coerces non-string keys via str().

Q12) UTF-8 BOM and Excel?

Answer Encoding utf-8-sig can help Excel recognize UTF-8 CSV on Windows.

Q13) Why create files inside the program?

Answer So demos run without shipping sidecar data files or depending on prior runs.

Q14) JSONL vs JSON array?

Answer JSONL is one JSON value per line; easier to stream and append than one giant array.

Q15) How to pretty-print JSON?

Answer json.dumps(obj, indent=2) or dump(..., indent=2).

L4

Simple Programs

Create and reload JSON config

import json
from pathlib import Path

path = Path("app_config.json")
config = {
    "app": "LearnCodeGuru",
    "levels": 6,
    "features": ["basics", "programs", "practice"],
}
with path.open("w", encoding="utf-8") as f:
    json.dump(config, f, indent=2)
with path.open("r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["app"], len(loaded["features"]))
print(path.read_text(encoding="utf-8"))

Create CSV grades then average

import csv
from pathlib import Path

path = Path("grades.csv")
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.writer(f)
    w.writerow(["name", "marks"])
    w.writerows([["Asha", 90], ["Bala", 78], ["Cara", 88]])

total = 0
count = 0
with path.open("r", encoding="utf-8", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        total += int(row["marks"])
        count += 1
print("average", round(total / count, 2))

JSON list filter to CSV

import csv
import json
from pathlib import Path

src = Path("students.json")
dst = Path("passed.csv")
students = [
    {"name": "Dev", "score": 55},
    {"name": "Esha", "score": 81},
    {"name": "Farah", "score": 73},
]
src.write_text(json.dumps(students, indent=2), encoding="utf-8")
passed = [s for s in json.loads(src.read_text(encoding="utf-8")) if s["score"] >= 70]
with dst.open("w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["name", "score"])
    w.writeheader()
    w.writerows(passed)
print(dst.read_text(encoding="utf-8"))

Round-trip DictWriter / DictReader

import csv
from pathlib import Path

path = Path("inventory.csv")
rows = [
    {"sku": "P1", "qty": "10"},
    {"sku": "P2", "qty": "4"},
]
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["sku", "qty"])
    w.writeheader()
    w.writerows(rows)
with path.open("r", encoding="utf-8", newline="") as f:
    data = list(csv.DictReader(f))
print(data)
print(sum(int(r["qty"]) for r in data))

JSONL event log

import json
from pathlib import Path

path = Path("events.jsonl")
with path.open("w", encoding="utf-8") as f:
    for evt in (
        {"user": "a", "action": "open"},
        {"user": "b", "action": "save"},
        {"user": "a", "action": "close"},
    ):
        f.write(json.dumps(evt) + "\n")

opens = 0
with path.open("r", encoding="utf-8") as f:
    for line in f:
        rec = json.loads(line)
        if rec["action"] == "open":
            opens += 1
print("open count", opens)

Custom date encoding to JSON file

import json
from datetime import date
from pathlib import Path

path = Path("schedule.json")
schedule = {
    "title": "Python stdlib",
    "day": date(2026, 10, 25),
}

class DateEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, date):
            return o.isoformat()
        return super().default(o)

with path.open("w", encoding="utf-8") as f:
    json.dump(schedule, f, cls=DateEncoder, indent=2)
loaded = json.loads(path.read_text(encoding="utf-8"))
print(loaded)
print(date.fromisoformat(loaded["day"]))

TSV export create-and-read

import csv
from pathlib import Path

path = Path("cities.tsv")
with path.open("w", encoding="utf-8", newline="") as f:
    w = csv.writer(f, delimiter="\t")
    w.writerow(["city", "code"])
    w.writerow(["Bengaluru", "BLR"])
    w.writerow(["Chennai", "MAA"])
with path.open("r", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f, delimiter="\t"):
        print(row["city"], row["code"])
L5

Problem Solving Tricks

  • Every file demo should create the file before reading it.
  • Open text files with encoding='utf-8'; CSV with newline=''.
  • Pretty JSON: indent=2; keep Unicode with ensure_ascii=False.
  • DictWriter.writeheader() before data rows.
  • Cast CSV fields: int(row['n']), float(...), never assume numbers.
  • Store dates as ISO strings in JSON.
  • Catch json.JSONDecodeError around untrusted input.
  • Use utf-8-sig when Excel must open the CSV.
  • Prefer pathlib Path for readable create/read demos.
  • JSONL: one dumps per line for append-friendly logs.
L6

Practice Programs List

  1. Write a JSON file of 3 courses and reload it.
  2. Create a CSV of expenses and print the total.
  3. Convert a JSON list of users to CSV with DictWriter.
  4. Add a custom JSONEncoder for date objects.
  5. Read a CSV you created and find the max score.
  6. Build a JSONL log and count events by type.
  7. Write TSV and read it with delimiter='\t'.
  8. Validate required keys after json.load.
  9. Demonstrate quoting by writing a field that contains commas.
  10. Atomic-write a JSON config via temp + replace.
  11. Flatten nested skills arrays into a pipe-separated CSV column.
  12. Compare dumps indent=2 vs compact size for the same object.