JSON Methods: JSON.parse() and JSON.stringify() in JavaScript Notes in Hindi & English : JSON पार्सिंग: JSON.parse() और JSON.stringify() में अंतर और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम JSON Methods: JSON.parse() and JSON.stringify() in JavaScript (JSON पार्सिंग: JSON.parse() और JSON.stringify() में अंतर) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: JSON.parse() converts JSON text into live JavaScript values with optional reviver transforms, while JSON.stringify() serializes objects into formatted JSON text with replacer filters and indentation.

अध्याय सार: JavaScript में JSON.parse() JSON स्ट्रिंग को वापस असली ऑब्जेक्ट में बदलता है और JSON.stringify() JavaScript ऑब्जेक्ट को नेटवर्क भेजने या localStorage में सहेजने के लिए JSON स्ट्रिंग में बदलता है।

JSON Methods: JSON.parse() and JSON.stringify() in JavaScript: Detailed Notes & Architecture (JSON पार्सिंग: JSON.parse() और JSON.stringify() में अंतर)

1. Deserialization with JSON.parse(text, reviver) (JSON.parse() द्वारा डेटा पार्सिंग)

[EN] JSON.parse(jsonString) validates and converts a raw JSON string received from fetch() or localStorage back into JavaScript objects/arrays. If the string breaks JSON grammar (like single quotes or trailing commas), JSON.parse() throws a SyntaxError, so wrapping external input in try...catch is essential. An optional reviver(key, value) function transforms parsed values—commonly converting ISO date strings back into Date objects.

[HI] JSON.parse() सर्वर या localStorage से मिली JSON स्ट्रिंग को असली JavaScript ऑब्जेक्ट या ऐरे में बदलता है। अमान्य सिंटैक्स पर यह SyntaxError फेंकता है, इसलिए इसे try...catch में चलाना सुरक्षित है। इसका reviver पैरामीटर मानों (जैसे Date स्ट्रिंग) को पार्स होते ही रूपांतरित कर सकता है।

2. Serialization Rules of JSON.stringify(value, replacer, space) (JSON.stringify() के नियम व पैरामीटर्स)

[EN] JSON.stringify(obj) converts JavaScript data into a JSON string. Keys whose values are undefined, functions, or Symbols inside an object are silently OMITTED; inside an array, those exact entries become null! Customizing behavior is easy: pass an array/function replacer as the 2nd argument to whitelist fields (e.g., omit passwords) and space (e.g., 2) as the 3rd argument for pretty-printing.

[HI] JSON.stringify() ऑब्जेक्ट को JSON स्ट्रिंग बनाता है। ऑब्जेक्ट के भीतर undefined या function वाली प्रॉपर्टी अपने आप छूट (omit) जाती हैं, जबकि ऐरे में वे null बन जाती हैं। दूसरे पैरामीटर replacer से चुनिंदा फ़ील्ड छांटे जाते हैं और तीसरे पैरामीटर space (जैसे 2) से सुंदर इंडेंटेशन मिलता है।

3. Handling toJSON() Hook & Circular References (toJSON() मेथड व सर्कुलर रेफरेंस त्रुटि)

[EN] If any object defines a .toJSON() method (including built-in Date.prototype.toJSON()), JSON.stringify() automatically invokes it instead of reading raw properties. Conversely, passing an object containing a circular reference (obj.self = obj) causes JSON.stringify() to throw a TypeError because JSON trees cannot represent cycles.

[HI] यदि किसी ऑब्जेक्ट में .toJSON() मेथड हो (जैसे Date में होता है), तो JSON.stringify() उसी का परिणाम उपयोग करता है। यदि किसी ऑब्जेक्ट में स्वयं का सर्कुलर रेफरेंस (a.self = a) हो, तो JSON.stringify() TypeError देता है।

4. Practical Web Uses: localStorage & Shallow vs Deep Cloning (localStorage व Deep Copy में उपयोग)

[EN] Because Web Storage (localStorage / sessionStorage) only stores string values, developers always wrap structured data using JSON.stringify() on write and JSON.parse() on read. Similarly, JSON.parse(JSON.stringify(obj)) quickly deep-clones simple plain data objects, though modern browsers now offer structuredClone(obj) to also handle Dates, Maps, Sets, and circular objects.

[HI] localStorage केवल स्ट्रिंग सहेजता है, इसलिए ऑब्जेक्ट सेव करते समय JSON.stringify() और पढ़ते समय JSON.parse() चलता है। आधुनिक JS में साधारण डीप-कॉपी के लिए structuredClone() और भी बेहतर विकल्प है।

Syntax, Formula & Technical Example (JSON Methods: JSON.parse() and JSON.stringify() in JavaScript)

const user = { id: 1, name: 'Anil', pwd: 'secret', temp: undefined, fn: () => {} };
const jsonStr = JSON.stringify(user, ['id', 'name'], 2); // Whitelist & indent 2
console.log(jsonStr);
const parsed = JSON.parse('{"score": 95}');
console.log(JSON.stringify([1, undefined, () => {}]));   // "[1,null,null]"

JSON Methods: JSON.parse() and JSON.stringify() in JavaScript Quick Reference & Comparison Table

Behavior CaseJSON.stringify() OutputImportant Exam Detail
Object key with undefined/functionKey is silently omitted completely{a:1, b:undefined} -> '{"a":1}'
Array element undefined/functionConverted to literal null[1, undefined] -> '[1,null]'
Circular object referenceThrows TypeError exceptionJSON format cannot model cycles
Invalid JSON passed to parse()Throws SyntaxError exceptionWrap JSON.parse() inside try...catch

JSON Methods: JSON.parse() and JSON.stringify() in JavaScript Top 20 Bilingual MCQs with Answers

Q1. What does JSON.stringify({ name: 'Asha', age: undefined, greet: () => 1 }) return?

(JSON.stringify({ name: 'Asha', age: undefined, greet: () => 1 }) का आउटपुट क्या होगा?)

(A) Throws TypeError

(B) '{"name":"Asha"}'

(C) '{"name":"Asha","age":null}'

(D) '{"name":"Asha","age":undefined}'

Correct Answer: (B)

[EN] JSON.stringify silently omits object properties whose values are undefined, functions, or Symbols.

[HI] ऑब्जेक्ट में undefined और function वाली प्रॉपर्टी को JSON.stringify पूरी तरह छोड़ देता है।

Q2. What does JSON.stringify([10, undefined, function(){}, 20]) return?

(JSON.stringify([10, undefined, function(){}, 20]) क्या स्ट्रिंग लौटाएगा?)

(A) '[10,undefined,null,20]'

(B) '[10,20]'

(C) '[10,null,null,20]'

(D) Throws TypeError

Correct Answer: (C)

[EN] Inside arrays, omitted elements would change array indices, so JSON.stringify converts undefined and functions to null.

[HI] ऐरे में इंडेक्स बनाए रखने के लिए undefined और function दोनों null में बदल जाते हैं।

Q3. Which error type is thrown if invalid syntax like JSON.parse("{'a':1}") executes?

(JSON.parse("{'a':1}") जैसे अमान्य JSON पर कौन सी एरर आती है?)

(A) SyntaxError

(B) TypeError

(C) RangeError

(D) ReferenceError

Correct Answer: (A)

[EN] Single quotes violate JSON syntax, causing JSON.parse() to throw a SyntaxError.

[HI] अमान्य JSON स्ट्रिंग होने पर JSON.parse() हमेशा SyntaxError देता है।

Q4. What does the 3rd argument (space) in JSON.stringify(obj, null, 4) control?

(JSON.stringify(obj, null, 4) में तीसरे पैरामीटर '4' का क्या कार्य है?)

(A) Restricts output to 4 keys

(B) Limits JSON depth to 4 nested levels

(C) Repeats serialization 4 times

(D) Adds 4-space indentation formatting (pretty printing) to the output string

Correct Answer: (D)

[EN] Passing a number (1-10) or string (like '\t') indents nested properties nicely for readability.

[HI] तीसरा आर्ग्यूमेंट आउटपुट स्ट्रिंग को पठनीय बनाने के लिए प्रति लेवल 4 स्पेस का इंडेंटेशन जोड़ता है।

Q5. Which type of error does JSON.stringify(obj) throw when obj contains a circular reference (obj.self = obj)?

(यदि obj.self = obj (सर्कुलर रेफरेंस) हो, तो JSON.stringify(obj) कौन सी एरर फेंकता है?)

(A) EvalError

(B) RangeError

(C) TypeError

(D) SyntaxError

Correct Answer: (C)

[EN] Detecting cyclic object values causes JSON.stringify() to throw TypeError: Converting circular structure to JSON.

[HI] सर्कुलर रेफरेंस मिलने पर JSON.stringify() TypeError फेंकता है।

Q6. What is the purpose of the optional 2nd parameter (reviver) in JSON.parse(text, reviver)?

(JSON.parse(text, reviver) में दूसरे पैरामीटर reviver फंक्शन का क्या उपयोग है?)

(A) Transforms parsed key/value pairs before returning the final object (e.g., converting ISO strings back to Date)

(B) Compresses memory arrays

(C) Validates HTML markup inside strings

(D) Indents the JSON string

Correct Answer: (A)

[EN] The reviver callback processes every key-value bottom-up to reconstruct custom objects like Dates.

[HI] reviver फंक्शन डेटा पार्स होते समय मानों (जैसे तारीख स्ट्रिंग को Date ऑब्जेक्ट में) बदलने का काम करता है।

Q7. How does Date object serialize when passed inside JSON.stringify({ created: new Date() })?

(JSON.stringify({ created: new Date() }) चलाने पर Date ऑब्जेक्ट किस रूप में बदलता है?)

(A) It is silently omitted like functions

(B) Into an ISO-8601 string via Date's built-in toJSON() method

(C) Throws DateSerializationError

(D) Into null

Correct Answer: (B)

[EN] Date implements Date.prototype.toJSON(), returning a UTC ISO string such as '2026-11-11T05:30:00.000Z'.

[HI] Date ऑब्जेक्ट में अंतर्निहित .toJSON() मेथड होता है जो उसे ISO-8601 स्ट्रिंग बना देता है।

Q8. What does passing an array of strings as the 2nd argument in JSON.stringify(user, ['id', 'email']) achieve?

(JSON.stringify(user, ['id', 'email']) में दूसरे पैरामीटर में ऐरे देने से क्या होता है?)

(A) Acts as an allowlist, serializing ONLY the 'id' and 'email' keys

(B) Excludes 'id' and 'email'

(C) Creates two separate JSON files

(D) Sorts all keys alphabetically

Correct Answer: (A)

[EN] An array replacer acts as a strict whitelist filtering which property names appear in the serialized JSON.

[HI] ऐरे replacer के रूप में देने पर आउटपुट में केवल उन्हीं चुनिंदा कीज़ ('id', 'email') को शामिल किया जाता है।

Q9. Why can localStorage.setItem('cart', obj) fail without JSON.stringify(obj)?

(localStorage.setItem('cart', obj) में बिना JSON.stringify() के ऑब्जेक्ट सेव करने पर क्या गड़बड़ी होती है?)

(A) It turns obj into XML

(B) localStorage stores strings only, turning obj into useless '[object Object]'

(C) localStorage throws StorageSecurityError

(D) obj deletes browser cookies

Correct Answer: (B)

[EN] Browser Storage coerces values via .toString(), creating '[object Object]' unless serialized cleanly via JSON.stringify().

[HI] localStorage हर डेटा को स्ट्रिंग बनाता है जिससे ऑब्जेक्ट '[object Object]' बन जाता है; इसलिए JSON.stringify जरूरी है।

Q10. What happens if you pass NaN or Infinity inside JSON.stringify({ x: NaN, y: Infinity })?

(JSON.stringify({ x: NaN, y: Infinity }) चलाने पर आउटपुट क्या प्राप्त होता है?)

(A) '{"x":NaN,"y":Infinity}'

(B) Throws SyntaxError

(C) Keys x and y are omitted

(D) '{"x":null,"y":null}'

Correct Answer: (D)

[EN] Because JSON lacks NaN/Infinity tokens, JS normalizes non-finite numbers to null during stringification.

[HI] JSON में NaN व Infinity न होने से JS इन्हें null में बदल देता है।

Q11. What does JSON.stringify(obj) invoke first if obj has a custom method named toJSON()?

(यदि किसी ऑब्जेक्ट में custom toJSON() मेथड परिभाषित हो, तो JSON.stringify(obj) किस डेटा को सिरियलाइज़ करता है?)

(A) Throws MethodConflictError

(B) Serializes the source code of toJSON()

(C) The return value of obj.toJSON()

(D) Only obj's enumerable properties, ignoring toJSON()

Correct Answer: (C)

[EN] Any object exposing .toJSON() overrides default serialization with the value returned by toJSON().

[HI] ऑब्जेक्ट में मौजूद .toJSON() मेथड की रिटर्न वैल्यू ही अंतिम JSON आउटपुट निर्धारित करती है।

Q12. What flaw occurs if you deep-clone an object containing Date objects or RegExp using JSON.parse(JSON.stringify(obj))?

(Date या RegExp वाले ऑब्जेक्ट की JSON.parse(JSON.stringify(obj)) से डीप-कॉपी करने पर क्या नुकसान होता है?)

(A) All numbers convert to strings

(B) Date turns into a plain String and RegExp turns into an empty object {}

(C) Throws TypeError always

(D) Date stays a Date instance

Correct Answer: (B)

[EN] JSON drops JS-specific prototypes, functions, undefined, Maps, and converts Dates to strings—use structuredClone() instead.

[HI] JSON क्लोनिंग से Date स्ट्रिंग बन जाता है और RegExp खाली {} हो जाता है; आधुनिक JS में structuredClone() उपयोग करें।

Q13. Which built-in global object houses both parse() and stringify()?

(parse() और stringify() मेथड्स किस मानक ग्लोबल ऑब्जेक्ट के अंतर्गत आते हैं?)

(A) Serializer

(B) JSON

(C) window.Text

(D) Object

Correct Answer: (B)

[EN] ES5 standardized the built-in JSON global namespace object (do NOT call 'new JSON()').

[HI] ECMAScript 5 से ग्लोबल JSON ऑब्जेक्ट दोनों मेथड उपलब्ध कराता है।

Q14. What does calling response.json() on a Fetch API Response object return?

(Fetch API में response.json() कॉल करने पर क्या वापस मिलता है?)

(A) A raw JSON string

(B) A Promise that resolves with the parsed JavaScript value (internally similar to JSON.parse)

(C) An XMLHttpRequest instance

(D) A synchronous JavaScript object immediately

Correct Answer: (B)

[EN] response.json() reads the HTTP body stream asynchronously and resolves a Promise with the parsed JS object/array.

[HI] response.json() बॉडी स्ट्रीम को एसिंक्रोनस तरीके से पढ़कर पार्स किए हुए ऑब्जेक्ट वाला Promise लौटाता है।

Q15. Does JSON.stringify({ a: 1, [Symbol('k')]: 2 }) include the Symbol key?

(क्या JSON.stringify({ a: 1, [Symbol('k')]: 2 }) Symbol कुंजी को JSON में शामिल करेगा?)

(A) Replaced with null

(B) Throws TypeError

(C) No, Symbol-keyed properties are completely ignored by JSON.stringify

(D) Yes, converted to string key

Correct Answer: (C)

[EN] JSON only serializes own enumerable string-keyed properties and completely skips Symbol keys.

[HI] JSON.stringify केवल स्ट्रिंग कीज़ लेता है और Symbol कीज़ को अनदेखा कर देता है।

Q16. What does typeof JSON.stringify({ id: 7 }) return?

(typeof JSON.stringify({ id: 7 }) का मान क्या होता है?)

(A) "array"

(B) "object"

(C) "string"

(D) "json"

Correct Answer: (C)

[EN] JSON.stringify always outputs serialized JSON formatted as a plain string.

[HI] JSON.stringify हमेशा एक JSON फॉर्मेटेड स्ट्रिंग लौटाता है।

Q17. Within JSON Methods: JSON.parse() and JSON.stringify() in JavaScript, which behavior case directly maps to: "Key is silently omitted completely"?

(JSON Methods: JSON.parse() and JSON.stringify() in JavaScript में कौन सा Behavior Case सीधे "Key is silently omitted completely" से संबंधित है?)

(A) Invalid JSON passed to parse()

(B) Array element undefined/function

(C) Circular object reference

(D) Object key with undefined/function

Correct Answer: (D)

[EN] In JSON Methods: JSON.parse() and JSON.stringify() in JavaScript, 'Object key with undefined/function' handles 'Key is silently omitted completely' ({a:1, b:undefined} -> '{"a":1}').

[HI] JSON Methods: JSON.parse() and JSON.stringify() in JavaScript में 'Object key with undefined/function' का कार्य/विवरण 'Key is silently omitted completely' ({a:1, b:undefined} -> '{"a":1}') है।

Q18. Which option accurately describes 'Array element undefined/function' in JSON Methods: JSON.parse() and JSON.stringify() in JavaScript?

(JSON Methods: JSON.parse() and JSON.stringify() in JavaScript के संदर्भ में 'Array element undefined/function' की सही विशेषता कौन सी है?)

(A) Throws SyntaxError exception

(B) Key is silently omitted completely

(C) Throws TypeError exception

(D) Converted to literal null

Correct Answer: (D)

[EN] 'Array element undefined/function' provides 'Converted to literal null' — key point: [1, undefined] -> '[1,null]'.

[HI] 'Array element undefined/function' का मुख्य विवरण 'Converted to literal null' है ([1, undefined] -> '[1,null]')।

Q19. In JSON Methods: JSON.parse() and JSON.stringify() in JavaScript, identify the correct parameter for the specification: "Throws TypeError exception".

(JSON Methods: JSON.parse() and JSON.stringify() in JavaScript में "Throws TypeError exception" विवरण किस विकल्प के लिए सही है?)

(A) Circular object reference

(B) Object key with undefined/function

(C) Invalid JSON passed to parse()

(D) Array element undefined/function

Correct Answer: (A)

[EN] 'Circular object reference' corresponds to 'Throws TypeError exception' (JSON format cannot model cycles).

[HI] 'Circular object reference' का संबंध 'Throws TypeError exception' (JSON format cannot model cycles) से है।

Q20. Considering JSON Methods: JSON.parse() and JSON.stringify() in JavaScript, what key behavior defines 'Invalid JSON passed to parse()'?

(JSON Methods: JSON.parse() and JSON.stringify() in JavaScript में 'Invalid JSON passed to parse()' की मुख्य भूमिका या मान क्या है?)

(A) Throws SyntaxError exception

(B) Converted to literal null

(C) Throws TypeError exception

(D) Key is silently omitted completely

Correct Answer: (A)

[EN] 'Invalid JSON passed to parse()' represents 'Throws SyntaxError exception' (Wrap JSON.parse() inside try...catch).

[HI] 'Invalid JSON passed to parse()' का अर्थ/मान 'Throws SyntaxError exception' है (Wrap JSON.parse() inside try...catch)।

JSON Methods: JSON.parse() and JSON.stringify() in JavaScript — Exam FAQs

Q1: Why is using eval('(' + jsonStr + ')') instead of JSON.parse(jsonStr) dangerous?

JSON.parse() के बजाय eval() से JSON पार्स करना खतरनाक क्यों है?

[EN] eval() executes arbitrary JavaScript code, creating instant Remote Code Execution / XSS vulnerabilities if the payload comes from an external server or user.

[HI] eval() किसी भी खतरनाक JavaScript कोड को चला सकता है, जिससे XSS हमला हो सकता है; JSON.parse() केवल सुरक्षित डेटा पार्स करता है।

Q2: How can I pretty-print an object nicely into browser console or <pre> tag?

ब्राउज़र <pre> टैग में सुंदर इंडेंटेशन के साथ JSON कैसे दिखाएं?

[EN] Use JSON.stringify(obj, null, 2) — the 2 adds clean two-space indentation at each nested level.

[HI] JSON.stringify(obj, null, 2) लिखने पर हर स्तर पर 2 स्पेस का साफ इंडेंटेशन आ जाता है।

Q3: What replaced JSON.parse(JSON.stringify(obj)) for deep cloning in modern JS?

आधुनिक JS में JSON आधारित डीप क्लोनिंग का बेहतर विकल्प क्या है?

[EN] Built-in global structuredClone(obj) safely clones nested objects, arrays, Dates, Maps, Sets, and circular references natively.

[HI] आधुनिक ब्राउज़र्स व Node.js में structuredClone(obj) उपलब्ध है जो Date, Map, Set व सर्कुलर ऑब्जेक्ट्स को भी क्लोन कर सकता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)