Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟡 Advanced Python  ·  Lesson 25

JSON और CSV Handling

एक मिनट में JSON और CSV

JSONCSV
दिखता है{"name": "Asha", "marks": [91, 88]}name,marks
Asha,91
किसके लिए सबसे अच्छाNested data, APIs, config filesTables: Excel, Google Sheets, reports
Python modulejsoncsv
Python में मिलता हैdict / listrows या dicts की list

दोनों modules Python में पहले से हैं – कुछ install नहीं करना। लगभग हर असली project इनमें से कोई format पढ़ता है: API responses JSON होते हैं, school और sales reports CSV।

JSON strings: dumps() और 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)
int, floatnumber
True / Falsetrue / false
Nonenull

JSON files: dump() और 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
💡 “s” याद रखें

dumps/loads strings के साथ; dump/load files के साथ। ensure_ascii=False लगाएँ ताकि Hindi, \u0916… नहीं बल्कि Hindi में save हो।

ग़लत JSON सुरक्षित संभालना

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 का True और आख़िरी comma valid JSON नहीं हैं। बाहर से आए data पर json.loads हमेशा try/except में रखें।

csv.DictReader से CSV पढ़ना

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 हमेशा strings होती हैं – गणित से पहले int()/float() से बदलें।
  • csv module quotes के अंदर के comma ("Singh, Kabir") सही संभालता है; line.split(",") टूट जाएगा।
  • Python docs के अनुसार newline="" के साथ खोलें।

csv.DictWriter से CSV लिखना

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 में Hindi ??? दिखती है

CSV को encoding="utf-8-sig" से save करें। अदृश्य BOM Excel को बताता है कि file UTF-8 है।

असली उदाहरण: web app के लिए CSV → JSON

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 } ]

ऐसे ही दुकान मालिक की Excel price list website या mobile app का data बनती है।

आम ग़लतियाँ

ग़लतीसुधार
Windows पर rows के बीच ख़ाली linesCSV को newline="" से खोलें
TypeError: Object of type datetime is not JSON serializableपहले बदलें: d.isoformat(), या json.dumps(x, default=str)
CSV के numbers जोड़ने पर “9188”Strings को int() से बदलें
पढ़ते समय UnicodeDecodeErrorencoding="utf-8" दें (Excel files के लिए "utf-8-sig")

अभ्यास

  1. 5 contacts (name, phone, city) की list को indent 2 के साथ contacts.json में save करके वापस load करें।
  2. marks.csv पढ़कर percentage column जोड़ें और marks_with_percent.csv लिखें।
  3. Orders की JSON list को ऐसी CSV में बदलें जो Hindi नामों के साथ Excel में सही खुले।
  4. safe_load(path) function लिखें जो JSON file न होने या ग़लत होने पर ख़ाली dict लौटाए।

सारांश

  • Strings के लिए json.dumps/loads, files के लिए json.dump/load; indent और ensure_ascii=False लगाएँ।
  • csv.DictReader/DictWriter इस्तेमाल करें, newline="" से खोलें, values को strings से बदलें।
  • Excel-friendly CSV के लिए utf-8-sig।
  • बाहर के data के लिए json.JSONDecodeError पकड़ें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या csv module की जगह pandas इस्तेमाल करें?
Analysis, filtering और बड़ी tables के लिए pandas.read_csv आसान है। छोटी scripts, बिना pandas वाले servers या साधारण reports के लिए built-in csv module काफ़ी है और कुछ install नहीं करना पड़ता।
मैंने numbers दिए फिर भी JSON keys strings क्यों हैं?
JSON object की keys हमेशा strings होती हैं। json.dumps({1: "a"}) से {"1": "a"} मिलता है। ज़रूरत हो तो load के बाद keys को int() से बदलें।
← Back to Python Tutorial
🔗

Share this topic with a friend

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

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

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

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicpip, venv और Project Environment आपकी प्रगति: 25 / 66 (38%) · Lesson 26 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें