JSON Formatter Python — json.dumps() गाइड
मुफ़्त JSON Formatter & Beautifier को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।
JSON Formatter & Beautifier ऑनलाइन आज़माएं →जब मैं Python API क्लाइंट को डीबग कर रहा होता हूँ, तो सबसे पहले python pretty print json का उपयोग करता हूँ — json.dumps(data, indent=4) का एक कॉल और एक अपठनीय single-line blob तुरंत navigable हो जाता है। Python का बिल्ट-इन json मॉड्यूल यह पूरी तरह standard library में संभालता है — कोई third-party install नहीं चाहिए। अगर बिना कोड लिखे तुरंत परिणाम चाहिए, तो ToolDeck का JSON Formatter यह तुरंत कर देता है। यह गाइड हर व्यावहारिक तरीका कवर करती है: json.dumps() के सभी पैरामीटर के साथ, pprint, orjson high-performance formatting के लिए, json.tool CLI, और API responses फॉर्मेट करने और disk से पढ़ने जैसे real-world scenarios — सभी Python 3.8+ compatible code के साथ। इसमें datetime और UUID जैसे custom types serialize करना, ijson से gigabyte-scale files stream करना, और rich से terminal syntax highlighting भी शामिल है।
- →
json.dumps(data, indent=4)Python की stdlib में version 2.6 से बिल्ट-इन है — कोई install नहीं चाहिए। - →जब भी आपके data में accented letters, CJK characters, हिंदी या emoji हों तो
ensure_ascii=Falseपास करें। - →
datetime,UUID, या custom classes के लिएdefault=पैरामीटर उपयोग करें याjson.JSONEncoderको subclass करें। - →
separators=(',', ':')सभी whitespace हटाता है — network transfer या URL embedding के लिए उपयोग करें। - →
orjsonstdlib से 5–10× तेज़ है औरdatetimeऔरuuid.UUIDको natively संभालता है। - →
pprint.pprint()Python syntax (True/None) आउटपुट करता है, valid JSON नहीं — files या API responses के लिए कभी उपयोग न करें। - →50 MB से बड़ी JSON files के लिए
json.load()की जगहijsonसे stream करें ताकिMemoryErrorसे बचा जा सके।
JSON Pretty Printing क्या है?
Pretty printing एक घने, minified JSON string को consistent indentation और line breaks के साथ human-readable format में बदलता है। यह transformation पूरी तरह cosmetic है: data identical है, केवल presentation बदलती है। Python का json मॉड्यूल यह standard library में पूरी तरह संभालता है — install करने की कोई ज़रूरत नहीं।
{"id":"usr_9f3a2b","name":"राहुल शर्मा","roles":["admin","editor"],"prefs":{"theme":"dark","lang":"hi"}}{
"id": "usr_9f3a2b",
"name": "राहुल शर्मा",
"roles": [
"admin",
"editor"
],
"prefs": {
"theme": "dark",
"lang": "hi"
}
}json.dumps() — JSON Format करने का मानक तरीका
json.dumps() Python 2.6 से Python की standard library का हिस्सा है — बस import json, कोई install नहीं चाहिए। यह किसी भी JSON-compatible Python object को formatted string में serialize करता है। मुख्य पैरामीटर है indent: readable output के लिए इसे 4 (या 2) पर सेट करें।
import json
user = {
"id": "usr_9f3a2b",
"name": "राहुल शर्मा",
"roles": ["admin", "editor"],
"prefs": {"theme": "dark", "lang": "hi"}
}
print(json.dumps(user, indent=4, ensure_ascii=False))
# Output:
# {
# "id": "usr_9f3a2b",
# "name": "राहुल शर्मा",
# "roles": [
# "admin",
# "editor"
# ],
# "prefs": {
# "theme": "dark",
# "lang": "hi"
# }
# }Production use के लिए अक्सर sort_keys=True (runs में consistent output) और ensure_ascii=False (non-ASCII characters readable रखें) चाहिए होगा:
import json
api_response = {
"timestamp": "2024-05-01T10:30:00Z",
"status": "success",
"data": {
"user_id": "usr_9f3a2b",
"display_name": "प्रिया पटेल",
"city": "दिल्ली",
"score": 4892.5,
"tags": ["python", "backend", "api"]
}
}
print(json.dumps(api_response, indent=4, sort_keys=True, ensure_ascii=False))
# Output (keys sorted, Hindi characters preserved):
# {
# "data": {
# "city": "दिल्ली",
# "display_name": "प्रिया पटेल",
# "score": 4892.5,
# "tags": ["api", "backend", "python"],
# "user_id": "usr_9f3a2b"
# },
# "status": "success",
# "timestamp": "2024-05-01T10:30:00Z"
# }json.dumps() एक string लौटाता है। Formatted JSON सीधे file में लिखने के लिए, json.dump(data, f, indent=4) उपयोग करें (बिना s के) — यह file object में लिखता है और memory में intermediate string बनाने से बचाता है।json.dumps() पैरामीटर संदर्भ
object को छोड़कर सभी पैरामीटर optional हैं। Defaults compact, ASCII-safe JSON उत्पन्न करते हैं — human-readable output के लिए पैरामीटर explicitly पास करें।
separators पैरामीटर से Compact JSON Output
डिफ़ॉल्ट रूप से json.dumps() items को ", " से और keys को values से ": " से अलग करता है।separators पैरामीटर दोनों को override करता है। (',', ':') पास करने से सभी whitespace हट जाता है और सबसे compact valid JSON मिलता है — network transmission, URL embedding, या database column में JSON store करने के लिए उपयोगी।
import json
payload = {
"endpoint": "/api/v2/events",
"filters": {"status": "active", "limit": 100},
"sort": "desc"
}
# Default — separators के बाद spaces (readable)
default_out = json.dumps(payload)
# {"endpoint": "/api/v2/events", "filters": {"status": "active", "limit": 100}, "sort": "desc"}
# len = 88
# Compact — बिल्कुल whitespace नहीं
compact_out = json.dumps(payload, separators=(',', ':'))
# {"endpoint":"/api/v2/events","filters":{"status":"active","limit":100},"sort":"desc"}
# len = 80 (9% छोटा; बड़े, deeply nested payloads पर savings बढ़ती है)
# Compact + sorted keys reproducible cache keys के लिए
canonical = json.dumps(payload, separators=(',', ':'), sort_keys=True)
print(canonical)
# {"endpoint":"/api/v2/events","filters":{"limit":100,"status":"active"},"sort":"desc"}indent= के साथ separators= पास करते हैं, तो separators argument केवल inline separators नियंत्रित करता है — indent से newlines और indentation preserved रहती है। Compact single-line output चाहिए तोindent छोड़ें (या None पास करें) और separators=(',', ':') सेट करें।default पैरामीटर से Custom Python Objects Serialize करना
Standard json मॉड्यूल dicts, lists, strings, numbers, booleans, और None serialize करता है — लेकिन किसी भी अन्य type पर TypeError throw करता है। Production code में सबसे आम culprits datetime objects और UUIDs हैं।
import json
from datetime import datetime, timezone
import uuid
order = {
"order_id": uuid.uuid4(), # ❌ TypeError: UUID is not JSON serializable
"placed_at": datetime.now(timezone.utc), # ❌ TypeError: datetime is not JSON serializable
"total_inr": 11900.50,
"items": ["pro-subscription", "addon-storage"]
}
json.dumps(order) # TypeError throw करता हैApproach 1 — default= पैरामीटर
default= को callable पास करें। json.dumps() इसे किसी भी ऐसे object के लिए call करता है जिसे वह handle नहीं कर सकता। serializable representation लौटाएं, या explicitly support न करने वाले types के लिए TypeError throw करें — unknown types को कभी silently ignore न करें।
import json
from datetime import datetime, timezone, date
import uuid
from decimal import Decimal
def json_default(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, uuid.UUID):
return str(obj)
if isinstance(obj, Decimal):
return float(obj)
raise TypeError(f"Type {type(obj).__name__!r} is not JSON serializable")
order = {
"order_id": uuid.uuid4(),
"placed_at": datetime(2024, 5, 1, 10, 30, 0, tzinfo=timezone.utc),
"total_inr": Decimal("11900.50"),
"items": ["pro-subscription", "addon-storage"]
}
print(json.dumps(order, indent=4, default=json_default))
# {
# "order_id": "a3f1c2d4-e5b6-7890-abcd-ef1234567890",
# "placed_at": "2024-05-01T10:30:00+00:00",
# "total_inr": 11900.5,
# "items": ["pro-subscription", "addon-storage"]
# }Approach 2 — json.JSONEncoder को subclass करना
Multiple modules में shared reusable encoding logic के लिए, json.JSONEncoder को subclass करना हर जगह default function thread करने से cleaner है। default method override करें और final fallback के रूप में super().default(obj) call करें — यह unsupported types के लिए correct error behavior preserve करता है।
import json
from datetime import datetime, timezone
import uuid
from decimal import Decimal
class AppEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, uuid.UUID):
return str(obj)
if isinstance(obj, Decimal):
return float(obj)
return super().default(obj) # unknown types के लिए TypeError throw करता है
order = {
"order_id": uuid.uuid4(),
"placed_at": datetime(2024, 5, 1, 10, 30, 0, tzinfo=timezone.utc),
"total_inr": Decimal("11900.50"),
}
# cls= के ज़रिए encoder class पास करें
print(json.dumps(order, indent=4, cls=AppEncoder))
# default= approach जैसा ही outputsuper().default(obj) call करें (या explicitly TypeError throw करें)। सब कुछ के लिए silently str(obj) लौटाने से वे objects corrupt हो जाएंगे जिन्हें error throw करना चाहिए था — production में trace करना मुश्किल bug।Decode वापस करना — object_hook
Encoding सिर्फ आधी कहानी है। JSON से custom Python object reconstruct करने के लिए, json.loads() या json.load() को object_hook function पास करें। Hook हर decoded JSON object (dict) के लिए call होता है और उसकी जगह कोई भी Python value लौटा सकता है — आपको पूरा encode ↔ decode round-trip देता है।
import json
from datetime import datetime
from dataclasses import dataclass
@dataclass
class Event:
name: str
occurred_at: datetime
user_id: str
def encode_event(obj):
if isinstance(obj, Event):
return {
"__type__": "Event",
"name": obj.name,
"occurred_at": obj.occurred_at.isoformat(),
"user_id": obj.user_id,
}
raise TypeError(f"Cannot serialize {type(obj)}")
def decode_event(d):
if d.get("__type__") == "Event":
return Event(
name=d["name"],
occurred_at=datetime.fromisoformat(d["occurred_at"]),
user_id=d["user_id"],
)
return d
# Encode
event = Event("login", datetime(2024, 5, 1, 10, 30), "usr_9f3a2b")
json_str = json.dumps(event, default=encode_event, indent=4)
# Event instance में वापस Decode करें
restored = json.loads(json_str, object_hook=decode_event)
print(type(restored)) # <class 'Event'>
print(restored.occurred_at) # 2024-05-01 10:30:00object_hook document में हर nested dict के लिए call होता है — सिर्फ top level के लिए नहीं। एक discriminator field शामिल करें (जैसे "__type__") ताकि hook आपके custom objects को plain dicts से distinguish कर सके जिन्हें as-is छोड़ना है।pprint — वैकल्पिक मॉड्यूल (और इसे कब न उपयोग करें)
Python का pprint मॉड्यूल (pretty printer) terminal में readability के लिए Python data structures format करता है। यह parsed Python objects पर काम करता है, JSON strings पर नहीं — और इसका output Python syntax उपयोग करता है, JSON syntax नहीं।
import json, pprint
raw = '{"sensor_id":"s-441","readings":[23.1,23.4,22.9],"unit":"celsius","active":true}'
data = json.loads(raw)
# pprint — valid Python repr, valid JSON नहीं
pprint.pprint(data, sort_dicts=False)
# {'sensor_id': 's-441',
# 'readings': [23.1, 23.4, 22.9],
# 'unit': 'celsius',
# 'active': True} ← Python True, JSON true नहीं
# json.dumps — valid JSON
print(json.dumps(data, indent=4))
# {
# "sensor_id": "s-441",
# "readings": [23.1, 23.4, 22.9],
# "unit": "celsius",
# "active": true ← valid JSON
# }pprint output को API endpoint पर कभी न भेजें या .json file में न लिखें — यह किसी भी JSON parser को तोड़ देगा जो standard syntax expect करता है। जो भी output valid JSON होना चाहिए उसके लिए json.dumps(indent=4) उपयोग करें।pprint कब उपयोगी है: REPL या debug log में Python objects का quick terminal inspection, विशेष रूप से जब object में non-JSON-serializable types हों (sets, custom class instances, conversion से पहले dataclasses)।
Requests से JSON Response को Pretty Print कैसे करें
सबसे आम real-world scenario: आपके पास disk पर JSON file है या API से HTTP response है, और debugging या logging के लिए format करना है। दोनों cases में same approach है — Python dict में parse करें, फिर json.dumps() से format करें।
File से पढ़ना
import json
try:
with open("config.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Console पर pretty-print करें
print(json.dumps(data, indent=4, ensure_ascii=False))
# या formatted version वापस disk पर लिखें
with open("config.pretty.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
except FileNotFoundError:
print(f"File not found: config.json")API response format करना
import json, requests
from requests.exceptions import HTTPError, ConnectionError, Timeout
def pretty_print_api(url: str) -> None:
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
print(json.dumps(resp.json(), indent=4, ensure_ascii=False))
except HTTPError as e:
print(f"HTTP {e.response.status_code}: {e}")
except (ConnectionError, Timeout) as e:
print(f"Network error: {e}")
except json.JSONDecodeError:
print(f"Response body JSON नहीं है:\n{resp.text[:500]}")
pretty_print_api("https://api.github.com/repos/python/cpython")response.json() response body पहले से parse करता है — अलग से json.loads() call करने की ज़रूरत नहीं।.json() access करने से पहले हमेशा raise_for_status() जोड़ें ताकि 4xx/5xx errors confusing parse error से पहले पकड़ी जा सकें।Command-Line Pretty Printing (कमांड-लाइन)
Python के साथ json.tool आता है, terminal से directly JSON format करने का एक CLI module — कोई Python script नहीं चाहिए। Python installed किसी भी machine पर available है।
# Local file format करें
python -m json.tool config.json
# API response को formatter से pipe करें
curl -s https://api.github.com/users/gvanrossum | python -m json.tool
# stdin से format करें
echo '{"service":"api-gateway","version":"2.1.0","healthy":true}' | python -m json.tool
# Keys को alphabetically sort करें
python -m json.tool --sort-keys data.json
# Custom indent (Python 3.9+)
python -m json.tool --indent 2 data.json--indent और --no-indent flags जोड़े। अधिक powerful terminal JSON filtering के लिए jq पर विचार करें — लेकिन python -m json.tool zero extra dependencies के साथ formatting use case कवर करता है।अगर आप terminal पर नहीं हैं — Postman response या log file पेस्ट कर रहे हैं — तो ToolDeck JSON Formatter एक ही स्टेप में पेस्ट, फॉर्मेट और कॉपी करने देता है, syntax highlighting और validation के साथ।
वैकल्पिक Libraries: orjson और rich
orjson — Native Type Support के साथ 5–10× तेज़
Standard json मॉड्यूल अधिकांश use cases के लिए काफी fast है, लेकिन अगर आप प्रति second हज़ारों objects serialize कर रहे हैं — logging pipelines, high-throughput APIs, large data exports — orjson 5–10× faster है। यह custom default function के बिना standard library जो serialize नहीं कर सकती उन्हें भी natively handle करता है: datetime, uuid.UUID, numpy arrays, और dataclasses।
pip install orjson
import orjson
from datetime import datetime, timezone
import uuid
event = {
"event_id": uuid.uuid4(), # str() नहीं चाहिए — orjson UUID handle करता है
"timestamp": datetime.now(timezone.utc), # isoformat() नहीं चाहिए
"service": "auth-service",
"level": "INFO",
"payload": {
"user_id": "usr_9f3a2b",
"action": "login",
"ip": "192.168.1.42",
"latency_ms": 34
}
}
# orjson.dumps bytes लौटाता है; .decode() str में convert करता है
print(orjson.dumps(event, option=orjson.OPT_INDENT_2).decode())
# {
# "event_id": "a3f1c2d4-e5b6-7890-abcd-ef1234567890",
# "timestamp": "2024-05-01T10:30:00+00:00",
# "service": "auth-service",
# ...
# }दो बातें जानने योग्य: orjson.dumps() bytes लौटाता है, string नहीं — string चाहिए तो .decode() call करें। यह केवल OPT_INDENT_2 के ज़रिए 2-space indentation support करता है; 4-space output के लिए standard json.dumps(indent=4) उपयोग करें।
rich — Terminal में Syntax Highlighting
अगर आप terminal या REPL में regularly JSON inspect करते हैं, rich color-coded, syntax-highlighted output render करता है जो deeply nested structures को एक नज़र में readable बनाता है। Keys, strings, numbers, और booleans में से हर एक को अलग रंग मिलता है — monochrome text की दीवार से scan करना कहीं आसान है। यह केवल debug-time tool है, production serialization के लिए नहीं।
pip install rich
from rich import print_json
import json
# print_json() JSON string accept करता है
raw = '{"event":"login","user_id":"usr_9f3a2b","timestamp":"2024-05-01T10:30:00Z","success":true,"meta":{"ip":"192.168.1.42","attempts":1}}'
print_json(raw)
# Python dict को pretty-print करने के लिए, पहले string में convert करें
data = {
"status": "success",
"count": 42,
"tags": ["python", "api", "backend"]
}
print_json(json.dumps(data))rich.print_json() terminal colour के लिए ANSI escape codes output करता है — इस output को capture करके .json file में कभी न लिखें या API response के रूप में न भेजें। किसी भी machine-readable output के लिए json.dumps(indent=4) उपयोग करें।simplejson — Drop-in stdlib Replacement
simplejson वह library है जो Python का standard json module बनी — यह अभी भी independently maintain है और minor features में stdlib से आगे रहती है। यह true drop-in replacement है: import बदलें और बाकी code unchanged। उपयोगी जब custom encoder के बिना Decimal support चाहिए, या older Python environments target कर रहे हों।
pip install simplejson
import simplejson as json # stdlib जैसा identical API
from decimal import Decimal
order = {
"item": "API subscription",
"price": Decimal("49.99"), # stdlib json यहाँ TypeError throw करता
"quantity": 3,
}
# simplejson Decimal natively serialize करता है — default= नहीं चाहिए
print(json.dumps(order, indent=4, use_decimal=True))
# {
# "item": "API subscription",
# "price": 49.99,
# "quantity": 3
# }orjson बेहतर choice है। simplejson तब उपयोग करें जब custom encoder लिखे बिना native Decimal serialization चाहिए, या ऐसी codebase maintain कर रहे हों जो पहले से इसे उपयोग करती है।Memory खत्म हुए बिना बड़ी JSON Files Process करना
json.load() एक भी field access करने से पहले पूरी file memory में read करता है। लाखों records वाली file या gigabyte से बड़े payload पर यह MemoryError cause करता है — या कम से कम process को swap पर जाकर crawl करने पर मजबूर करता है।
ijson से Streaming
ijson एक streaming JSON parser है जो file object से एक-एक item generate करता है। पूरे dataset को memory में hold किए बिना array elements iterate करते हैं — peak memory file size की बजाय एक object के proportional रहती है।
pip install ijson
import ijson
from decimal import Decimal
# events.json structure: {"events": [...लाखों objects...]}
total_revenue = Decimal("0")
login_count = 0
with open("events.json", "rb") as f: # ijson को binary mode चाहिए
for event in ijson.items(f, "events.item"):
if event.get("type") == "purchase":
total_revenue += Decimal(str(event["amount_inr"]))
elif event.get("type") == "login":
login_count += 1
print(f"Revenue: ₹{total_revenue:.2f} | Logins: {login_count}")
# 2 GB file को ~30 MB peak memory usage से process करता हैjson.load() से ijson पर switch करें। उस threshold से नीचे json.load() simpler और काफी faster है क्योंकि internally C-extension parser उपयोग करता है। 100 MB से ऊपर, streaming से memory savings extra overhead से ज़्यादा होती है।NDJSON — प्रति line एक JSON object
NDJSON (Newline Delimited JSON, JSON Lines या .jsonl भी कहते हैं) प्रति line एक complete JSON object store करता है। Log exporters, Kafka consumers, और data pipelines यह format अक्सर produce करते हैं क्योंकि हर line independently append और read हो सकती है — record add करने के लिए पूरी file parse करने की ज़रूरत नहीं। Standard library इसे बिना extra dependencies के handle करती है।
import json
from pathlib import Path
# NDJSON लिखें — एक event per line
events = [
{"ts": "2024-05-01T10:00:00Z", "user": "usr_9f3a2b", "action": "login"},
{"ts": "2024-05-01T10:01:03Z", "user": "usr_9f3a2b", "action": "purchase", "sku": "pro-plan"},
{"ts": "2024-05-01T10:15:42Z", "user": "usr_4ab1d9", "action": "login"},
]
with open("events.ndjson", "w", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
# NDJSON पढ़ें — constant memory, file size कितनी भी बड़ी हो
purchase_count = 0
with open("events.ndjson", "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line: # blank lines skip करें
continue
event = json.loads(line)
if event.get("action") == "purchase":
purchase_count += 1
print(f"{event['ts']} — {event['user']} ने {event['sku']} खरीदा")सामान्य गलतियाँ
मैंने ये चार गलतियाँ लगभग हर कोड रिव्यू में देखी हैं जिनमें JSON serialization शामिल है — विशेष रूप से JavaScript से आने वाले developers में जहाँ JSON.stringify encoding automatically handle करता है।
समस्या: dict पर print() Python repr उपयोग करता है — output True/None (Python syntax) दिखाता है, true/null (JSON syntax) नहीं। यह valid JSON नहीं है।
समाधान: Valid, readable JSON output के लिए हमेशा json.dumps(data, indent=4) उपयोग करें।
data = {"active": True, "count": None}
print(data)
# {'active': True, 'count': None}print(json.dumps(data, indent=4))
# {
# "active": true,
# "count": null
# }समस्या: Hindi/special characters (हिंदी अक्षर, emoji) \\uXXXX sequences में escape हो जाते हैं, जिससे output अपठनीय हो जाता है।
समाधान: Original Unicode characters preserve करने के लिए ensure_ascii=False पास करें।
user = {"name": "प्रिया पटेल", "city": "मुंबई"}
json.dumps(user, indent=2)
# {"name": "\u092a\u094d\u0930\u093f\u092f\u093e ...", ...}json.dumps(user, indent=2, ensure_ascii=False)
# {"name": "प्रिया पटेल", "city": "मुंबई"}समस्या: json.dumps() string लौटाता है; फिर अलग f.write() call चाहिए, एक unnecessary intermediate string create होती है।
समाधान: json.dump(data, f, indent=4) उपयोग करें — यह सीधे file object में लिखता है।
with open("out.json", "w") as f:
f.write(json.dumps(data, indent=4))with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)समस्या: pprint.pprint() Python syntax (True, None, single quotes) उपयोग करता है जिसे JSON parsers reject करते हैं।
समाधान: JSON के रूप में parseable होने वाले किसी भी output के लिए json.dumps(indent=4) उपयोग करें।
import pprint
pprint.pprint({"running": True, "last_error": None})
# {'running': True, 'last_error': None}import json
print(json.dumps({"running": True, "last_error": None}, indent=4))
# {"running": true, "last_error": null}Method Comparison — json.dumps, orjson, simplejson, rich (तुलना)
रोजमर्रा की formatting और file writes के लिए json.dumps() उपयोग करें — zero dependencies के साथ 95% use cases cover करता है। Hot path में serialize करते समय या datetime और UUID fields वाले objects के लिए orjson उपयोग करें। Out-of-the-box Decimal support के साथ drop-in stdlib compatibility चाहिए तो simplejson उपयोग करें।rich.print_json() और pprint को strictly local terminal inspection के लिए reserve करें — दोनों machine-readable output नहीं produce करते।
अक्सर पूछे जाने वाले सवाल
Python में JSON को pretty print कैसे करें?
json.dumps(data, indent=4) कॉल करें। indent पैरामीटर प्रति नेस्टिंग स्तर स्पेस की संख्या निर्धारित करता है। पहले json मॉड्यूल import करें — यह Python की standard library के साथ आता है, इसलिए pip install की ज़रूरत नहीं। अगर आपके डेटा में non-ASCII अक्षर जैसे हिंदी, CJK या emoji हैं तो ensure_ascii=False पास करें।
import json
user = {"username": "rahul_s", "plan": "enterprise", "permissions": ["read", "write", "deploy"]}
print(json.dumps(user, indent=4, ensure_ascii=False))json.dumps() और json.dump() में क्या अंतर है?
json.dumps() ("s" के साथ) मेमोरी में एक फॉर्मेटेड स्ट्रिंग लौटाता है। json.dump() ("s" के बिना) सीधे एक file-like ऑब्जेक्ट में लिखता है — दूसरे आर्गुमेंट के रूप में खुला फ़ाइल हैंडल पास करें। डिस्क पर फॉर्मेटेड JSON लिखने के लिए, json.dump(data, f, indent=4) मुहावरेदार है और intermediate स्ट्रिंग बनाने से बचाता है।
# dumps → मेमोरी में स्ट्रिंग
formatted = json.dumps(data, indent=4)
# dump → सीधे फ़ाइल में लिखें
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4)json.dumps() असली अक्षर की जगह \uXXXX क्यों दिखाता है?
डिफ़ॉल्ट रूप से ensure_ascii=True हर non-ASCII अक्षर को \uXXXX सीक्वेंस में escape करता है। मूल Unicode अक्षर संरक्षित रखने के लिए ensure_ascii=False सेट करें। यह हिंदी नाम, पते और किसी भी user-generated content के लिए विशेष रूप से महत्वपूर्ण है।
data = {"city": "मुंबई", "greeting": "नमस्ते"}
# डिफ़ॉल्ट — escaped
json.dumps(data, indent=4)
# {"city": "\u092e\u0941\u0902\u092c\u0908", ...}
# पठनीय
json.dumps(data, indent=4, ensure_ascii=False)
# {"city": "मुंबई", "greeting": "नमस्ते"}JSON स्ट्रिंग (dict नहीं) को pretty print कैसे करें?
पहले json.loads() से स्ट्रिंग parse करें, फिर json.dumps() से फॉर्मेट करें। त्वरित टर्मिनल इंस्पेक्शन के लिए दोनों कॉल को एक लाइन में chain किया जा सकता है।
import json
raw = '{"endpoint":"/api/v2/users","timeout":30,"retry":true}'
print(json.dumps(json.loads(raw), indent=4))क्या Python में JSON फॉर्मेट करने के लिए pprint का उपयोग कर सकते हैं?
pprint.pprint() Python ऑब्जेक्ट representation पैदा करता है, वैध JSON नहीं। यह true/false/null (JSON syntax) की जगह True/False/None (Python syntax) उपयोग करता है। pprint आउटपुट को कभी भी API या JSON parser को न भेजें — json.dumps(indent=4) उपयोग करें।
import pprint, json
data = {"active": True, "score": None}
pprint.pprint(data) # {'active': True, 'score': None} ← JSON नहीं
json.dumps(data, indent=4) # {"active": true, "score": null} ← वैध JSONPython में JSON keys को वर्णानुक्रम से कैसे sort करें?
json.dumps() में sort_keys=True जोड़ें। कमांड लाइन के लिए python -m json.tool --sort-keys data.json उपयोग करें। सॉर्ट किए गए keys JSON diffs को पठनीय बनाते हैं और बदले हुए values को आसानी से पहचानने में मदद करते हैं।
import json
server = {"workers": 4, "host": "0.0.0.0", "port": 8080, "debug": False}
print(json.dumps(server, indent=4, sort_keys=True))
# {
# "debug": false,
# "host": "0.0.0.0",
# "port": 8080,
# "workers": 4
# }Python आपको पूरा नियंत्रण देता है — कस्टम serializers, streaming, pipeline integration. जब सिर्फ एक formatted snippet inspect या share करना हो, तो ToolDeck का JSON Formatter तेज़ रास्ता है: JSON पेस्ट करें और बिना किसी environment setup के indented, highlighted result पाएं।
संबंधित टूल्स
Maria is a backend developer specialising in Python and API integration. She has broad experience with data pipelines, serialisation formats, and building reliable server-side services. She is an active member of the Python community and enjoys writing practical, example-driven guides that help developers solve real problems without unnecessary theory.
Dmitri is a DevOps engineer who relies on Python as his primary scripting and automation language. He builds internal tooling, CI/CD pipelines, and infrastructure automation scripts that run in production across distributed teams. He writes about the Python standard library, subprocess management, file processing, encoding utilities, and the practical shell-adjacent Python that DevOps engineers use every day.