JSON Formatter JavaScript — JSON.stringify()
मुफ़्त JSON Formatter & Beautifier को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।
JSON Formatter & Beautifier ऑनलाइन आज़माएं →जब मैं Node.js में API रिस्पॉन्स डीबग करता हूँ, तो minified JSON की एक दीवार पहली चीज़ है जो मुझे धीमा करती है — एक बार JSON.stringify(data, null, 2) कॉल करने से स्ट्रक्चर तुरंत पठनीय हो जाता है। JavaScript में JSON फॉर्मेट करने के लिए runtime से ज़्यादा कुछ नहीं चाहिए: JSON.stringify हर ब्राउज़र और Node.js environment में बिल्ट-इन है, कोई install नहीं चाहिए। अगर आपको बिना कोड लिखे सिर्फ त्वरित परिणाम चाहिए, तो ToolDeck का JSON Formatter यह तुरंत कर देता है। यह गाइड सब कुछ व्यावहारिक रूप से कवर करती है: space पैरामीटर, replacer ऐरे और फ़ंक्शन, Date, BigInt और circular references हैंडल करना, Node.js (18+) में JSON फ़ाइलें पढ़ना और लिखना, CLI से pretty-printing, और production serialization के लिए fast-json-stringify लाइब्रेरी।
- ✓JSON.stringify(data, null, 2) हर ब्राउज़र और Node.js में बिल्ट-इन है — install नहीं चाहिए।
- ✓replacer पैरामीटर एक array (key whitelist) या function (वैल्यू ट्रांसफ़ॉर्म) स्वीकार करता है — sensitive फ़ील्ड mask करने के लिए इसका उपयोग करें।
- ✓Date ऑब्जेक्ट toJSON() → ISO 8601 स्ट्रिंग के ज़रिए अपने-आप सीरियलाइज़ होते हैं; BigInt TypeError देता है और कस्टम replacer की ज़रूरत होती है।
- ✓Circular references TypeError देती हैं — replacer function में seen Set से ठीक करें, या flatted लाइब्रेरी इस्तेमाल करें।
- ✓CLI pretty-printing के लिए node -p "JSON.stringify(require('./file.json'),null,2)" इस्तेमाल करें — कोई अतिरिक्त टूल नहीं चाहिए।
JSON फॉर्मेटिंग क्या है?
JSON फॉर्मेटिंग (जिसे pretty-printing भी कहते हैं) एक कॉम्पैक्ट, minified JSON स्ट्रिंग को consistent इंडेंटेशन और लाइन ब्रेक के साथ human-readable लेआउट में बदल देती है। अंदर का डेटा एक जैसा रहता है — सिर्फ whitespace बदलती है। Compact JSON network transfer के लिए बेहतर है जहाँ हर byte मायने रखती है; formatted JSON debugging, code review और log inspection के लिए बेहतर है। JavaScript का JSON.stringify() एक ही कॉल में space पैरामीटर टॉगल करके दोनों काम करता है।
{"orderId":"ord_8f2a91bc","status":"shipped","items":[{"sku":"HDMI-4K-2M","qty":2,"unitPrice":12.99}],"total":25.98}{
"orderId": "ord_8f2a91bc",
"status": "shipped",
"items": [
{
"sku": "HDMI-4K-2M",
"qty": 2,
"unitPrice": 12.99
}
],
"total": 25.98
}JSON.stringify() — बिल्ट-इन JSON फॉर्मेटर
JSON.stringify() हर JavaScript environment में एक global function है — browsers, Node.js, Deno, Bun — बिना किसी import के। इसका तीसरा आर्गुमेंट space इंडेंटेशन कंट्रोल करता है: प्रति लेवल उतने स्पेस के लिए नंबर पास करें, या टैब के लिए '\t' स्ट्रिंग पास करें। इसे छोड़ें (या null पास करें) और आपको compact single-line output मिलेगा।
const serverConfig = {
host: "api.payments.internal",
port: 8443,
workers: 4,
tls: { enabled: true, cert: "/etc/ssl/certs/api.pem" },
rateLimit: { requestsPerMinute: 1000, burst: 50 }
}
console.log(JSON.stringify(serverConfig, null, 2))
// {
// "host": "api.payments.internal",
// "port": 8443,
// "workers": 4,
// "tls": {
// "enabled": true,
// "cert": "/etc/ssl/certs/api.pem"
// },
// "rateLimit": {
// "requestsPerMinute": 1000,
// "burst": 50
// }
// }space पैरामीटर एक नंबर (1–10 स्पेस) या स्ट्रिंग स्वीकार करता है। टैब कैरेक्टर पास करने से ऐसा output मिलता है जो कई editors और diff tools पसंद करते हैं। आप तीनों पैरामीटर को मिला भी सकते हैं — यहाँ एक real-world pattern है जिसे मैं config फ़ाइलों में formatted JSON लिखते समय इस्तेमाल करता हूँ:
const telemetryEvent = {
eventId: "evt_3c7f9a2b",
service: "checkout-api",
severity: "warn",
latencyMs: 342,
region: "eu-west-1",
tags: ["payment", "timeout", "retry"]
}
// 2-स्पेस इंडेंट (JS प्रोजेक्ट में सबसे आम)
JSON.stringify(telemetryEvent, null, 2)
// टैब इंडेंट (कुछ linters और config tools की पसंद)
JSON.stringify(telemetryEvent, null, '\t')
// Compact — कोई whitespace नहीं (network transfer के लिए)
JSON.stringify(telemetryEvent)
// {"eventId":"evt_3c7f9a2b","service":"checkout-api",...}undefined, functions और Symbol वैल्यू output से चुपचाप हटा दी जाती हैं। अगर किसी property की वैल्यू undefined है, तो वो key serialized स्ट्रिंग में बिल्कुल भी नहीं दिखेगी — यह optional fields वाले objects log करते समय bugs का एक आम स्रोत है।Replacer फ़ंक्शन — Output फ़िल्टर और ट्रांसफ़ॉर्म करें
JSON.stringify() का दूसरा आर्गुमेंट replacer है। यह दो रूपों में आता है: एक array जो specific keys को whitelist करता है, या एक function जो हर key/value pair के लिए कॉल होती है और वैल्यू को फ़िल्टर, ट्रांसफ़ॉर्म या redact कर सकती है। मैं array form तब इस्तेमाल करता हूँ जब मुझे जल्दी एक subset चाहिए, और function form तब जब logging से पहले sensitive data mask करनी हो।
Array Replacer — Specific Keys Whitelist करें
const order = {
orderId: "ord_8f2a91bc",
customer: {
id: "usr_4421",
email: "raj.kumar@udaharan.com",
passwordHash: "bcrypt:$2b$12$XKzV..."
},
items: [{ sku: "HDMI-4K-2M", qty: 2, unitPrice: 12.99 }],
createdAt: "2026-03-10T14:22:00Z"
}
// log output में केवल safe fields शामिल करें
const safeLog = JSON.stringify(order, ["orderId", "items", "createdAt"], 2)
// {
// "orderId": "ord_8f2a91bc",
// "items": [{ "sku": "HDMI-4K-2M", "qty": 2, "unitPrice": 12.99 }],
// "createdAt": "2026-03-10T14:22:00Z"
// }
// passwordHash और customer.email बाहर रखे गएFunction Replacer — वैल्यू ट्रांसफ़ॉर्म करें
const auditRecord = {
requestId: "req_7d2e91",
user: { id: "usr_4421", email: "raj.kumar@udaharan.com", apiKey: "sk-live-eKx9..." },
action: "update_billing",
timestamp: new Date("2026-03-10T14:22:00Z"),
durationMs: 87
}
function safeReplacer(key, value) {
// secrets या PII जैसे दिखने वाले fields को redact करें
if (key === "apiKey") return "[गोपनीय]"
if (key === "email") return value.replace(/(?<=.{2}).+(?=@)/, "***")
return value
}
console.log(JSON.stringify(auditRecord, safeReplacer, 2))
// {
// "requestId": "req_7d2e91",
// "user": { "id": "usr_4421", "email": "ra.***@udaharan.com", "apiKey": "[गोपनीय]" },
// "action": "update_billing",
// "timestamp": "2026-03-10T14:22:00.000Z",
// "durationMs": 87
// }this के रूप में current key वाले ऑब्जेक्ट के साथ कॉल किया जाता है। पहली कॉल में key के रूप में empty string और serialized की जाने वाली पूरी वैल्यू पास होती है — normal serialization जारी रखने के लिए इसे unchanged रिटर्न करें।Non-Serializable Types हैंडल करना
सभी JavaScript values JSON से cleanly map नहीं होतीं। यह जानना कि हर type कैसे behave करती है, production code में silent data loss और unexpected runtime errors को रोकता है।
Date — toJSON() के ज़रिए Automatic
Date objects एक toJSON() method implement करते हैं जो ISO 8601 string रिटर्न करती है। JSON.stringify() serializing से पहले toJSON() को automatically कॉल करता है, इसलिए कोई custom handling नहीं चाहिए।
const webhook = {
eventType: "payment.succeeded",
occurredAt: new Date("2026-03-10T14:22:00Z"),
processedAt: new Date()
}
JSON.stringify(webhook, null, 2)
// {
// "eventType": "payment.succeeded",
// "occurredAt": "2026-03-10T14:22:00.000Z",
// "processedAt": "2026-03-10T14:22:01.347Z"
// }
// toJSON() method वाला कोई भी object ऐसे ही handle होता है:
const custom = { toJSON: () => "custom-value", hidden: 42 }
JSON.stringify(custom) // '"custom-value"'Custom Classes — toJSON() Implement करें
कोई भी class एक toJSON() method implement कर सकती है और JSON.stringify() serialization के दौरान उसे automatically कॉल करेगा। यह domain types के लिए global replacer से ज़्यादा साफ़ है जो पूरे codebase में दिखती हैं।
class Money {
constructor(amount, currency) {
this.amount = amount
this.currency = currency
}
toJSON() {
// JSON.stringify द्वारा automatically कॉल किया जाता है
return { amount: this.amount, currency: this.currency, formatted: `${this.currency} ${this.amount.toFixed(2)}` }
}
}
class OrderId {
constructor(id) { this.id = id }
toJSON() { return this.id } // Plain string के रूप में serialize करें
}
const invoice = {
invoiceId: new OrderId('inv_8f2a91bc'),
subtotal: new Money(199.00, 'INR'),
tax: new Money(15.92, 'INR'),
issuedAt: new Date('2026-03-10T14:22:00Z')
}
JSON.stringify(invoice, null, 2)
// {
// "invoiceId": "inv_8f2a91bc",
// "subtotal": { "amount": 199, "currency": "INR", "formatted": "INR 199.00" },
// "tax": { "amount": 15.92, "currency": "INR", "formatted": "INR 15.92" },
// "issuedAt": "2026-03-10T14:22:00.000Z"
// }toJSON() replacer function से पहले priority लेता है। अगर दोनों मौजूद हैं, toJSON() पहले चलता है — replacer को original class instance की जगह already-converted value मिलती है।BigInt — Replacer के बिना TypeError
// यह error देता है: TypeError: Do not know how to serialize a BigInt
// JSON.stringify({ sessionId: 9007199254741234n })
// समाधान: replacer में BigInt को string में convert करें
function bigIntReplacer(_key, value) {
return typeof value === 'bigint' ? value.toString() : value
}
const metrics = {
requestCount: 9007199254741234n, // Number.MAX_SAFE_INTEGER से अधिक
service: "ingestion-worker",
region: "us-east-1"
}
JSON.stringify(metrics, bigIntReplacer, 2)
// {
// "requestCount": "9007199254741234",
// "service": "ingestion-worker",
// "region": "us-east-1"
// }Circular References — Seen Set के बिना TypeError
// यह error देता है: TypeError: Converting circular structure to JSON
// const node = { id: "n1" }; node.self = node; JSON.stringify(node)
// समाधान: WeakSet से देखे गए objects ट्रैक करें
function circularReplacer() {
const seen = new WeakSet()
return function (_key, value) {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]'
seen.add(value)
}
return value
}
}
const parent = { id: "node_parent", label: "मूल" }
const child = { id: "node_child", parent }
parent.child = child // circular
JSON.stringify(parent, circularReplacer(), 2)
// {
// "id": "node_parent",
// "label": "मूल",
// "child": { "id": "node_child", "parent": "[Circular]" }
// }
// वैकल्पिक: npm install flatted
// import { stringify } from 'flatted'
// stringify(parent) // circular refs को natively हैंडल करता हैJSON.stringify() पैरामीटर संदर्भ
तीनों पैरामीटर हर आधुनिक JavaScript runtime में पूरी तरह सपोर्टेड हैं। Defaults compact single-line JSON produce करते हैं — readable output के लिए पैरामीटर explicitly पास करें।
File और API रिस्पॉन्स से JSON फॉर्मेट करना
Node.js (18+) में आपको अक्सर JSON config file को reformat करना होता है या debugging के लिए API response को pretty-print करना होता है। दोनों patterns में same two-step approach इस्तेमाल होता है: raw text को JSON.parse() से parse करें, फिर JSON.stringify() से re-serialize करें।
JSON Config File पढ़ना और Rewrite करना
import { readFileSync, writeFileSync } from 'fs'
try {
const raw = readFileSync('./config/database.json', 'utf8')
const config = JSON.parse(raw)
writeFileSync('./config/database.json', JSON.stringify(config, null, 2))
console.log('Config सफलतापूर्वक reformat हो गया')
} catch (err) {
console.error('Config reformat नहीं हो सका:', err.message)
// JSON.parse SyntaxError देगा अगर फ़ाइल में invalid JSON है
// readFileSync ENOENT देगा अगर फ़ाइल मौजूद नहीं है
}Async File Reformat (fs/promises)
import { readFile, writeFile } from 'fs/promises'
async function reformatJson(filePath) {
const raw = await readFile(filePath, 'utf8')
const parsed = JSON.parse(raw)
const formatted = JSON.stringify(parsed, null, 2)
await writeFile(filePath, formatted, 'utf8')
return { keys: Object.keys(parsed).length }
}
// उपयोग
const { keys } = await reformatJson('./config/feature-flags.json')
console.log(`${keys} top-level keys reformat हुए`)fetch() रिस्पॉन्स से JSON Pretty Print करना
Node.js 18+ या browser में API client build या debug करते समय, response body को pretty-print करना server ने क्या return किया यह समझने का सबसे तेज़ तरीका है। Standard pattern है response.json() (parsed object) फिर JSON.stringify(). अगर पहले raw string चाहिए — जैसे hash compute करने या verbatim log करने के लिए — तो response.text() फिर JSON.parse() इस्तेमाल करें।
// Pattern 1: response.json() → pretty print
async function debugEndpoint(url) {
const res = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` }
})
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`)
const data = await res.json()
console.log(JSON.stringify(data, null, 2))
}
await debugEndpoint('https://api.stripe.com/v1/charges?limit=3')// Pattern 2: response.text() → parse → format
// उपयोगी जब raw response और pretty-print दोनों log करना हो
async function inspectRawResponse(url) {
const res = await fetch(url)
const raw = await res.text()
console.log('Raw response की लंबाई:', raw.length)
try {
const parsed = JSON.parse(raw)
console.log('Formatted:')
console.log(JSON.stringify(parsed, null, 2))
} catch {
console.error('Response valid JSON नहीं है:', raw.slice(0, 200))
}
}Command Line से Pretty Printing
Node.js बिना किसी additional tool के terminal से JSON pretty-print करने की पर्याप्त क्षमता के साथ आता है। ये one-liners CI scripts, deployment pipelines और shell aliases में उपयोगी हैं। और भी तेज़ interactive use के लिए jq install करें — command line पर JSON manipulation का de-facto standard।
# node -p (print) से package.json pretty-print करें
node -p "JSON.stringify(require('./package.json'), null, 2)"
# stdin से pretty-print (pipe-friendly, CI में काम करता है)
echo '{"port":3000,"env":"production"}' | node -e "
const d = require('fs').readFileSync(0, 'utf8')
console.log(JSON.stringify(JSON.parse(d), null, 2))
"
# फ़ाइल में save API response को pretty-print करें
cat api-response.json | node -e "
process.stdin.setEncoding('utf8')
let s = ''
process.stdin.on('data', c => s += c)
process.stdin.on('end', () => console.log(JSON.stringify(JSON.parse(s), null, 2)))
"# Python fallback (macOS और अधिकतर Linux distros पर pre-installed)
cat api-response.json | python3 -m json.tool
# jq — सबसे तेज़ और feature-rich (brew install jq / apt install jq)
cat api-response.json | jq .
# jq — एक ही step में pretty-print और filter
cat api-response.json | jq '.data.users[] | {id, email}'"type": "module" के साथ), require() one-liners में उपलब्ध नहीं है। इसके बजाय --input-type=module और fs.readFileSync इस्तेमाल करें, या ऊपर दिखाए अनुसार CommonJS snippet के साथ node -e पर switch करें।अगर आप terminal पर हैं ही नहीं — Postman response या log file paste कर रहे हैं — तो ToolDeck का JSON Formatter आपको syntax highlighting और built-in validation के साथ एक ही step में paste, format और copy करने देता है।
High-Performance Alternative — fast-json-stringify
fast-json-stringify JSON Schema से एक dedicated serializer function generate करती है। क्योंकि यह data का shape पहले से जानती है, यह type-checking skip कर सकती है और recursive descent की जगह string concatenation इस्तेमाल करती है — benchmarks आमतौर पर बड़े, repetitive payloads पर JSON.stringify() की तुलना में 2–5× throughput improvement दिखाते हैं। मैं इसे high-frequency API routes में इस्तेमाल करता हूँ जहाँ serialization cost profiler traces में दिखती है।
npm install fast-json-stringify
import fastJson from 'fast-json-stringify'
const serializeTelemetryEvent = fastJson({
title: 'TelemetryEvent',
type: 'object',
properties: {
eventId: { type: 'string' },
service: { type: 'string' },
severity: { type: 'string', enum: ['info', 'warn', 'error'] },
latencyMs: { type: 'integer' },
timestamp: { type: 'string' },
region: { type: 'string' }
},
required: ['eventId', 'service', 'severity', 'latencyMs', 'timestamp']
})
const event = {
eventId: 'evt_3c7f9a2b',
service: 'checkout-api',
severity: 'warn',
latencyMs: 342,
timestamp: new Date().toISOString(),
region: 'eu-west-1'
}
const json = serializeTelemetryEvent(event)
// '{"eventId":"evt_3c7f9a2b","service":"checkout-api","severity":"warn",...}'fast-json-stringify structured data के production serialization के लिए designed है — यह हमेशा compact output produce करती है (pretty-printing नहीं)। Development के दौरान human-readable output के लिए, सामान्य रूप से JSON.stringify(data, null, 2) इस्तेमाल करें।Syntax Highlighting के साथ Terminal Output
Node.js का बिल्ट-इन util.inspect() terminal display के लिए optimized colored, human-readable output produce करता है। यह circular references और BigInt को natively handle करता है, और nested objects को किसी भी depth तक recursively render करता है। Output valid JSON नहीं है — यह JavaScript syntax इस्तेमाल करता है (जैसे functions और Symbols को छोड़ने की जगह render करता है), जो इसे Node.js debugging scripts के लिए ideal बनाता है लेकिन API responses या file output के लिए unsuitable।
import { inspect } from 'util'
const payload = {
requestId: "req_7d2e91",
user: { id: "usr_4421", roles: ["admin", "billing"] },
metadata: { ipAddress: "203.0.113.42", userAgent: "Mozilla/5.0" },
createdAt: new Date()
}
// depth: null → सभी nested levels expand करें; colors: true → ANSI terminal colors
console.log(inspect(payload, { colors: true, depth: null }))util.inspect() इस्तेमाल न करें। इसका output valid JSON नहीं है और किसी भी downstream system में parse errors का कारण बनेगा जो इस पर JSON.parse() call करता है। इसे केवल interactive terminal debugging के लिए रखें।Large JSON Files के साथ काम करना
JSON.parse() parsing से पहले पूरी file को memory में load करता है — छोटे payloads के लिए ठीक है, लेकिन database exports, application log dumps, या analytics batches जैसी 50–100 MB से ऊपर की files के लिए practical नहीं। इन cases के लिए Node.js Streams और stream-json library आपको heap को blow किए बिना records को एक-एक करके process करने देती है।
stream-json से Streaming Parsing
npm install stream-json
import { pipeline } from 'stream/promises'
import { createReadStream } from 'fs'
import { parser } from 'stream-json'
import { streamArray } from 'stream-json/streamers/StreamArray.js'
// events.json = लाखों objects का array — कभी पूरा memory में load नहीं होता
await pipeline(
createReadStream('./events.json'),
parser(),
streamArray(),
async function* (source) {
for await (const { value: event } of source) {
if (event.severity === 'error') {
console.log(JSON.stringify(event, null, 2))
}
}
}
)NDJSON / JSON Lines — कोई Extra Dependencies नहीं
NDJSON (Newline Delimited JSON) प्रति line एक JSON object store करता है और Kafka exports, BigQuery outputs, और structured log pipelines में आम है। Node.js का बिल्ट-इन readline बिना third-party packages के इसे handle करता है।
import { createReadStream } from 'fs'
import { createInterface } from 'readline'
// Format: प्रति line एक JSON object (logs, Kafka exports, BigQuery)
const rl = createInterface({
input: createReadStream('./logs.ndjson'),
crlfDelay: Infinity
})
for await (const line of rl) {
if (!line.trim()) continue
const entry = JSON.parse(line)
if (entry.level === 'error') {
console.log(JSON.stringify(entry, null, 2))
}
}JSON.parse() से streaming पर switch करें। NDJSON / JSON Lines के लिए readline इस्तेमाल करें — कोई extra dependencies नहीं चाहिए।सामान्य गलतियाँ
ये चार गलतियाँ code reviews और production bug reports में बार-बार दिखती हैं। हर एक में JSON.stringify() का एक subtle behavior शामिल है जिसे miss करना आसान है और बाद में debug करना मुश्किल।
समस्या: undefined values वाली object properties JSON output से पूरी तरह हटा दी जाती हैं — कोई warning या error नहीं। जब object में optional fields होते हैं तो इससे invisible data loss होता है।
समाधान: उन intentionally absent values के लिए null इस्तेमाल करें जो serialized output में दिखनी चाहिए। undefined केवल उन fields के लिए रखें जिन्हें JSON से exclude किया जाना चाहिए।
const userProfile = {
userId: "usr_4421",
displayName: "राज कुमार",
avatarUrl: undefined, // चुपचाप गायब हो जाएगा
bio: undefined // चुपचाप गायब हो जाएगा
}
JSON.stringify(userProfile, null, 2)
// { "userId": "usr_4421", "displayName": "राज कुमार" }
// avatarUrl और bio गायब — कोई warning नहींconst userProfile = {
userId: "usr_4421",
displayName: "राज कुमार",
avatarUrl: null, // intentionally absent — output में दिखता है
bio: null // intentionally absent — output में दिखता है
}
JSON.stringify(userProfile, null, 2)
// {
// "userId": "usr_4421",
// "displayName": "राज कुमार",
// "avatarUrl": null,
// "bio": null
// }समस्या: JSON.stringify() को BigInt value pass करने से runtime पर TypeError आती है। यह silent omission नहीं, एक hard crash है — production में तब दिखेगा जब कोई numeric field Number.MAX_SAFE_INTEGER से ज़्यादा हो।
समाधान: एक replacer function इस्तेमाल करें जो serialization से पहले BigInt values को strings में convert करे। वैकल्पिक रूप से, JSON.stringify को pass करने से पहले data layer में BigInt को string या Number में convert करें।
const session = {
sessionId: 9007199254741234n, // BigInt literal
userId: "usr_4421",
startedAt: "2026-03-10T14:00:00Z"
}
JSON.stringify(session, null, 2)
// Uncaught TypeError: Do not know how to serialize a BigIntfunction bigIntReplacer(_key, value) {
return typeof value === 'bigint' ? value.toString() : value
}
const session = {
sessionId: 9007199254741234n,
userId: "usr_4421",
startedAt: "2026-03-10T14:00:00Z"
}
JSON.stringify(session, bigIntReplacer, 2)
// {
// "sessionId": "9007199254741234",
// "userId": "usr_4421",
// "startedAt": "2026-03-10T14:00:00Z"
// }समस्या: जो objects खुद को reference करते हैं — DOM trees, linked lists, और कुछ ORM result sets में आम — वे JSON.stringify() को pass करने पर TypeError देते हैं। Error केवल serialization के समय होती है, अक्सर जहाँ circular reference बना था वहाँ से बहुत दूर।
समाधान: Circular references detect और replace करने के लिए WeakSet के साथ replacer function इस्तेमाल करें, या circular structures को natively handle करने वाली flatted library install करें।
const dept = { id: "dept_eng", name: "इंजीनियरिंग" }
const team = { id: "team_frontend", dept }
dept.teams = [team] // circular: dept → team → dept
JSON.stringify(dept, null, 2)
// Uncaught TypeError: Converting circular structure to JSONimport { stringify } from 'flatted' // npm install flatted
const dept = { id: "dept_eng", name: "इंजीनियरिंग" }
const team = { id: "team_frontend", dept }
dept.teams = [team]
// flatted circular refs handle करता है — नोट: output flatted format में है, standard JSON नहीं
stringify(dept)
// या standard JSON output के लिए WeakSet-based replacer इस्तेमाल करें:
function circularReplacer() {
const seen = new WeakSet()
return (_key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]'
seen.add(value)
}
return value
}
}
JSON.stringify(dept, circularReplacer(), 2)समस्या: JSON.stringify() को 10 से ज़्यादा space value pass करने से कोई error नहीं आती — value चुपचाप 10 तक cap हो जाती है। Deep nesting के लिए 20 spaces per indent expect करने वाले developers को केवल 10 मिलेंगे, जिससे generated files में unexpected formatting होगी।
समाधान: Maximum indentation 10 spaces है। Deep structures के लिए 2-space indentation prefer करें (JavaScript projects में सबसे आम convention) और navigation के लिए collapsible editors पर rely करें।
const deepConfig = { server: { tls: { certs: { primary: "/etc/ssl/api.pem" } } } }
// 20-space indent expect कर रहे हैं — लेकिन space 10 पर cap है
JSON.stringify(deepConfig, null, 20)
// JSON.stringify(deepConfig, null, 10) जैसा ही output
// कोई error नहीं, कोई warning नहीं — चुपचाप truncate हुआconst deepConfig = { server: { tls: { certs: { primary: "/etc/ssl/api.pem" } } } }
// 2 (अधिकतर projects) या 4 spaces इस्तेमाल करें — कभी 10 से ज़्यादा नहीं
JSON.stringify(deepConfig, null, 2)
// {
// "server": {
// "tls": {
// "certs": {
// "primary": "/etc/ssl/api.pem"
// }
// }
// }
// }JSON.stringify बनाम Alternatives — त्वरित तुलना
अलग-अलग situations के लिए अलग-अलग tools। JSON.stringify replacer के साथ बिना किसी dependencies के अधिकतर production use cases cover करता है। util.inspect quick terminal debugging के लिए सही choice है जब color output चाहिए और valid JSON नहीं चाहिए। fast-json-stringify high-throughput routes में तब काम आता है जब profiling serialization cost दिखाए; बाकी सब चीज़ों के लिए schema maintenance का overhead उचित नहीं है।
अक्सर पूछे जाने वाले सवाल
JavaScript में JSON को सुंदर तरीके से कैसे प्रिंट करें?
JSON.stringify(data, null, 2) कॉल करें — तीसरा आर्गुमेंट इंडेंटेशन कंट्रोल करता है। स्पेस के लिए 2 या 4 पास करें, या टैब के लिए "\t" पास करें। कोई import या install नहीं चाहिए: JSON हर JavaScript environment में एक global ऑब्जेक्ट है, जिसमें ब्राउज़र और Node.js दोनों शामिल हैं।
const config = { host: "api.payments.internal", port: 8443, tls: true }
console.log(JSON.stringify(config, null, 2))
// {
// "host": "api.payments.internal",
// "port": 8443,
// "tls": true
// }JSON.stringify() में `space` पैरामीटर क्या करता है?
space पैरामीटर आउटपुट में इंडेंटेशन कंट्रोल करता है। प्रति लेवल उतने स्पेस के लिए एक नंबर (1–10) पास करें, या टैब कैरेक्टर के लिए "\t" जैसी स्ट्रिंग पास करें। 10 से ऊपर की वैल्यू चुपचाप 10 तक सीमित हो जाती है। null, 0 पास करने या पैरामीटर छोड़ने से कॉम्पैक्ट सिंगल-लाइन JSON मिलता है।
const data = { service: "payments", version: 3, active: true }
JSON.stringify(data, null, 2) // 2-स्पेस इंडेंट
JSON.stringify(data, null, 4) // 4-स्पेस इंडेंट
JSON.stringify(data, null, '\t') // टैब इंडेंट
JSON.stringify(data) // कॉम्पैक्ट: {"service":"payments","version":3,"active":true}JSON.stringify() कुछ वैल्यू के लिए undefined क्यों लौटाता है?
JSON.stringify उन ऑब्जेक्ट प्रॉपर्टीज़ को चुपचाप छोड़ देता है जिनकी वैल्यू undefined, function या Symbol है — इन टाइप्स का JSON में कोई रिप्रेजेंटेशन नहीं होता। अगर टॉप-लेवल वैल्यू खुद undefined है, तो function "undefined" स्ट्रिंग की जगह undefined रिटर्न करती है। ऐसे ऑप्शनल फ़ील्ड्स के लिए undefined की जगह null इस्तेमाल करें जिन्हें आउटपुट में दिखाई देना हो।
const event = {
traceId: "tr_9a2f",
handler: () => {}, // function — छोड़ा गया
requestId: undefined, // undefined — छोड़ा गया
sessionId: Symbol("s"), // Symbol — छोड़ा गया
status: "ok"
}
JSON.stringify(event, null, 2)
// { "traceId": "tr_9a2f", "status": "ok" }JSON फॉर्मेट करते समय Date ऑब्जेक्ट को कैसे हैंडल करें?
Date ऑब्जेक्ट में एक बिल्ट-इन toJSON() मेथड होती है जो ISO 8601 स्ट्रिंग रिटर्न करती है, इसलिए JSON.stringify इन्हें अपने आप हैंडल करता है। डेट्स के लिए कस्टम replacer की ज़रूरत नहीं है — सीरियलाइज़ड वैल्यू "2026-03-10T14:22:00.000Z" जैसी स्ट्रिंग होगी।
const order = {
orderId: "ord_8f2a91bc",
placedAt: new Date("2026-03-10T14:22:00Z"),
total: 42.98
}
JSON.stringify(order, null, 2)
// {
// "orderId": "ord_8f2a91bc",
// "placedAt": "2026-03-10T14:22:00.000Z",
// "total": 42.98
// }JavaScript में JSON स्ट्रिंग (ऑब्जेक्ट नहीं) को कैसे फॉर्मेट करें?
पहले JSON.parse() से स्ट्रिंग को पार्स करें, फिर JSON.stringify() से दोबारा सीरियलाइज़ करें। तेज़ डीबगिंग के लिए दोनों कॉल्स को एक ही लाइन में चेन किया जा सकता है।
const raw = '{"endpoint":"/api/v2/users","timeout":30,"retry":true}'
const formatted = JSON.stringify(JSON.parse(raw), null, 2)
console.log(formatted)
// {
// "endpoint": "/api/v2/users",
// "timeout": 30,
// "retry": true
// }क्या JSON.stringify() ब्राउज़र में इस्तेमाल की जा सकती है?
हाँ। JSON IE8 से हर आधुनिक ब्राउज़र में एक बिल्ट-इन global है — कोई script टैग या import नहीं चाहिए। DevTools कंसोल खोलें और JSON.stringify() सीधे कॉल करें। यह Node.js वर्शन से बिल्कुल एक जैसा काम करता है, उसी पैरामीटर सिग्नेचर और BigInt व circular references के बारे में उन्हीं सीमाओं के साथ।
// Chrome, Firefox, Safari, Edge में काम करता है — कोई import नहीं चाहिए
const payload = { userId: "usr_7b3c", action: "checkout", cart: ["SKU-001", "SKU-002"] }
copy(JSON.stringify(payload, null, 2)) // copy() एक DevTools हेल्पर हैJavaScript आपको पूरा control देता है — replacer functions, custom toJSON(), Node.js में बड़ी files की processing। जब आपको सिर्फ एक formatted snippet inspect या share करना हो, ToolDeck का JSON Formatter सबसे तेज़ रास्ता है: JSON paste करें और बिना किसी environment setup के formatted, highlighted result पाएं।
संबंधित टूल
Alex is a front-end and Node.js developer with extensive experience building web applications and developer tooling. He is passionate about web standards, browser APIs, and the JavaScript ecosystem. In his spare time he contributes to open-source projects and writes about modern JavaScript patterns, performance optimisation, and everything related to the web platform.
Marcus specialises in JavaScript performance, build tooling, and the inner workings of the V8 engine. He has spent years profiling and optimising React applications, working on bundler configurations, and squeezing every millisecond out of critical rendering paths. He writes about Core Web Vitals, JavaScript memory management, and the tools developers reach for when performance really matters.