Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟡 Advanced Python  ·  Lesson 25

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

JSONCSV
Looks like{"name": "Asha", "marks": [91, 88]}name,marks
Asha,91
Best forNested data, APIs, config filesTables: Excel, Google Sheets, reports
Python modulejsoncsv
Python type you getdict / listlist 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()

Python – json_strings.py
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__)
{"name": "Asha", "class": 12, "subjects": ["Maths", "IP"], "fees_paid": true, "rank": null} str IP dict
PythonJSON
dictobject {}
list, tuplearray []
strstring (double quotes only)
int, floatnumber
True / Falsetrue / false
Nonenull

JSON files: dump() and load()

Python – json_files.py
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"]))
{ "school": "Alpine Public School", "city": "खुर्जा", "session": "2026-27", "sections": [ "A", "B" ] } खुर्जा 2
💡 Remember the “s”

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

Python – json_errors.py
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)
valid : {'ok': True} invalid: {'ok': True} → Expecting property name enclosed in double quotes invalid: {"ok": true,} → Illegal trailing comma before end of object

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

Python – csv_read.py
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}")
{'name': 'Asha', 'maths': '91', 'science': '88', 'english': '79'} Asha total=258 avg=86.0 Ravi total=192 avg=64.0 Singh, Kabir total=131 avg=43.7
  • 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

Python – csv_write.py
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())
name,total,grade Asha,258,A Ravi,192,B "Singh, Kabir",131,C
⚠️ Excel shows Hindi as ???

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

Python – csv_to_json.py
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())
[ { "id": 1, "name": "Kaju Katli", "price": 900.0, "in_stock": true }, { "id": 2, "name": "Kalakand", "price": 600.0, "in_stock": false } ]

This is how a shop owner’s Excel price list becomes data for a website or mobile app.

Common mistakes

MistakeFix
Blank lines between rows on WindowsOpen CSV with newline=""
TypeError: Object of type datetime is not JSON serializableConvert first: d.isoformat(), or json.dumps(x, default=str)
Adding numbers from CSV gives “9188”Convert strings with int()
UnicodeDecodeError while readingPass encoding="utf-8" (or "utf-8-sig" for Excel files)

Practice tasks

  1. Save a list of 5 contacts (name, phone, city) as contacts.json with indent 2 and load it back.
  2. Read marks.csv, add a percentage column and write marks_with_percent.csv.
  3. Convert a JSON list of orders into a CSV that opens correctly in Excel with Hindi names.
  4. Write a function safe_load(path) that returns an empty dict if the JSON file is missing or invalid.

Summary

  • json.dumps/loads for strings, json.dump/load for files; use indent and ensure_ascii=False.
  • Use csv.DictReader/DictWriter, open with newline="", convert values from strings.
  • Use utf-8-sig for Excel-friendly CSV.
  • Catch json.JSONDecodeError for outside data.

Frequently Asked Questions

Should I use pandas instead of the csv module?
For analysis, filtering and large tables, pandas.read_csv is easier. For small scripts, servers without pandas, or writing simple reports, the built-in csv module is enough and has no installation.
Why are my JSON keys strings even though I used numbers?
JSON object keys are always strings. json.dumps({1: "a"}) gives {"1": "a"}. Convert keys back with int() after loading if needed.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicpip, venv and Project Environment Your progress: 25 / 66 (38%) · Lesson 26 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free