🟡 Advanced Python · Lesson 25
JSON और CSV Handling
एक मिनट में JSON और CSV
| JSON | CSV | |
|---|---|---|
| दिखता है | {"name": "Asha", "marks": [91, 88]} | name,marks |
| किसके लिए सबसे अच्छा | Nested data, APIs, config files | Tables: Excel, Google Sheets, reports |
| Python module | json | csv |
| Python में मिलता है | dict / list | rows या 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
| Python | JSON |
|---|---|
| dict | object {} |
| list, tuple | array [] |
| str | string (सिर्फ़ double quotes) |
| int, float | number |
| True / False | true / false |
| None | null |
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 के बीच ख़ाली lines | CSV को newline="" से खोलें |
TypeError: Object of type datetime is not JSON serializable | पहले बदलें: d.isoformat(), या json.dumps(x, default=str) |
| CSV के numbers जोड़ने पर “9188” | Strings को int() से बदलें |
| पढ़ते समय UnicodeDecodeError | encoding="utf-8" दें (Excel files के लिए "utf-8-sig") |
अभ्यास
- 5 contacts (name, phone, city) की list को indent 2 के साथ
contacts.jsonमें save करके वापस load करें। marks.csvपढ़करpercentagecolumn जोड़ें औरmarks_with_percent.csvलिखें।- Orders की JSON list को ऐसी CSV में बदलें जो Hindi नामों के साथ Excel में सही खुले।
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() से बदलें।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
