Python और JSON — loads, dumps और API data
🌐 यह page Hindi में है · Dictionary Hindi में पढ़ें →
loads बनाम loadtrue/false/nullNested dataAPI data
चार functions — s का मतलब string
JSON module के चार मुख्य functions हैं। s वाला suffix string पर काम करता है, बिना s वाला file पर। यही फर्क याद रख लो तो आधी उलझन खत्म।
import json
json.loads(text) # string -> Python object
json.dumps(obj) # Python -> string
json.load(f) # file -> Python object
json.dump(obj, f) # Python -> file
# s = string, बिना s = file handle
json.loads('{"a": 1}') # {'a': 1}
json.dumps({'a': 1}) # '{"a": 1}'
with open("data.json", encoding="utf-8") as f:
data = json.load(f) # file से पढ़ना
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)import json
json.load('{"a": 1}')
# 💥 AttributeError: 'str' object has no attribute 'read'
# load() को file चाहिए, string नहीं — string के लिए loads() है
true, false, null — तीन अलग शब्द
यही वो जगह है जहाँ NameError: name 'true' is not defined आता है। JSON का शब्दकोश JavaScript जैसा है, Python जैसा नहीं।
JSON Python
true -> True
false -> False
null -> None
import json
json.loads('{"active": true, "nickname": null}')
# {'active': True, 'nickname': None} — json खुद बदल देता हैdata = {"active": true} # 💥 NameError: name 'true' is not defined
data = {"active": True} # ✅ Python में True लिखो
# और JSON text को eval() कभी मत करो
raw = '{"active": true}'
eval(raw) # 💥 NameError — और सुरक्षा खतरा भी
json.loads(raw) # ✅ यही सही तरीकाeval() से JSON parse करना दो वजह से गलत है: JSON के true/null Python में नहीं हैं, और eval() कोई भी code चला देता है। हमेशा json.loads()।
Nested data से value निकालना
API responses गहरे nested होते हैं, और वही KeyError की सबसे बड़ी जगह है।
raw = '''
{
"user": {
"name": "Asha",
"address": {"city": "Delhi", "pin": "110001"},
"tags": ["admin", "dev"]
},
"count": 3
}
'''
data = json.loads(raw)
data["user"]["name"] # 'Asha'
data["user"]["address"]["city"] # 'Delhi'
data["user"]["tags"][0] # 'admin'
data["user"].get("phone", "—") # '—' — key नहीं है, error नहींdata["user"]["phone"]
# 💥 KeyError: 'phone'
data["user"]["address"]["state"]
# 💥 KeyError: 'state'# ✅ हर level पर get() — गहरे nested data के लिए सुरक्षित
city = data.get("user", {}).get("address", {}).get("city", "unknown")
# ✅ या try/except जब पूरा रास्ता चाहिए
try:
state = data["user"]["address"]["state"]
except KeyError:
state = "unknown"
# ✅ items की list पर loop
for item in data.get("items", []):
print(item.get("id"), item.get("name")).get(key, {}) की chain सबसे काम की तरकीब है: हर level पर खाली dict fallback देने से अगला .get() कभी fail नहीं होता।
API response संभालना
import json, urllib.request
url = "https://api.example.com/users"
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.loads(resp.read().decode("utf-8"))
# requests हो तो और आसान
import requests
resp = requests.get(url, timeout=10)
resp.raise_for_status() # 4xx/5xx पर exception
users = resp.json() # parse अपने आप
# हमेशा shape check करो — API बदल सकता है
if not isinstance(users, list):
raise ValueError(f"expected a list, got {type(users).__name__}")
for u in users:
print(u.get("id"), u.get("name", "(no name)"))तीन आदतें जो bugs बचाती हैं: timeout हमेशा दो (वरना request हमेशा के लिए अटक सकती है), raise_for_status() call करो (वरना 404 का error page data बन जाएगा), और shape check करो।
लिखते वक्त के ज़रूरी options
data = {"name": "आशा", "marks": 91.5, "items": [1, 2, 3]}
json.dumps(data)
# '{"name": "\\u0906\\u0936\\u0906", ...}' — Devanagari escape हो गया!
json.dumps(data, ensure_ascii=False)
# '{"name": "आशा", ...}' — पढ़ने लायक
json.dumps(data, ensure_ascii=False, indent=2) # सुंदर output
json.dumps(data, sort_keys=True) # keys क्रम में
json.dumps(data, separators=(",", ":")) # सबसे छोटा
# file में — वही options, साथ में encoding
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)ensure_ascii=False सबसे ज़्यादा छूटने वाला option है। इसके बिना हिन्दी और बाकी non-ASCII text escape sequences में बदल जाता है — valid है, पर इंसान के पढ़ने लायक नहीं। और file खोलते वक्त encoding="utf-8" हमेशा दो।
JSON क्या नहीं कर सकता
import json
from datetime import datetime
json.dumps({"when": datetime.now()})
# 💥 TypeError: Object of type datetime is not JSON serializable
json.dumps({"nums": {1, 2, 3}})
# 💥 TypeError: Object of type set is not JSON serializable
# ✅ default function दो
def fallback(obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return sorted(obj)
raise TypeError(f"cannot serialize {type(obj).__name__}")
json.dumps({"when": datetime.now(), "nums": {1, 2}}, default=fallback)JSON सिर्फ छह types जानता है: object (dict), array (list), string, number, true/false, null। Python के datetime, set, tuple और class instances इसमें नहीं हैं — default= से रास्ता बताओ।
आम गलतियाँ
load()औरloads()उलट लेना।loads()string लेता है,load()file। यही सबसे आम गलती है।- JSON text में
true/nullलिखना। Python मेंTrue/None— और JSON text कोeval()कभी मत करो। - गहरे nested data पर सीधा
[]use करना।.get(key, {})chain याtry/exceptलिखो। ensure_ascii=Falseभूल जाना। हिन्दी text escape sequences में बदल जाएगा।- API response का shape मान लेना। API बदल सकता है;
isinstancecheck और.get()use करो। timeoutन देना। Network request हमेशा के लिए अटक सकती है।
import json
json.loads('{"a": 1,}') # 💥 JSONDecodeError: trailing comma
# Python dict में ठीक है, JSON में नहीं
json.loads("{'a': 1}") # 💥 single quotes JSON में नहीं चलतीं
json.loads('{"a": 1}') # ✅
🛠️ Practice करो (free, browser में)
पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।
- Nested dictionary access — गहरे nested data तक पहुँचना।
- dict.get() with a default — KeyError से बचाव।
अक्सर पूछे जाने वाले सवाल
loads और load में क्या फर्क है?
loads() string parse करता है, load() file object से पढ़ता है। s का मतलब string है। dumps() और dump() में वही फर्क है — एक string बनाता है, दूसरा file में लिखता है।
JSON में true क्यों error देता है?
क्योंकि true, false और null JavaScript और JSON के शब्द हैं, Python के नहीं। Python में True, False और None लिखो। json.loads() ये बदलाव खुद कर देता है।
गहरे nested JSON से value कैसे निकालें?
हर level पर .get(key, {}) की chain लगाओ — data.get('user', {}).get('address', {}).get('city', 'unknown')। इससे कोई भी level खाली हो तो भी KeyError नहीं आता।
हिन्दी text escape क्यों हो जाता है?
क्योंकि json.dumps() का ensure_ascii डिफ़ॉल्ट रूप से True है। ensure_ascii=False दो, और file खोलते वक्त encoding='utf-8' भी।
datetime को JSON में कैसे लिखें?
JSON में datetime नहीं होता, इसलिए TypeError मिलता है। dumps(..., default=fallback) दो और fallback में obj.isoformat() लौटाओ। वही तरीका set और custom classes पर भी काम करता है।