Lesson 45: Mastering JavaScript JSON methods with challenges!

JSON (JavaScript Object Notation) is a lightweight data-interchange format. JavaScript provides two core methods to handle it:
JSON.stringify(value, replacer, space)
โ Converts a JavaScript object into a JSON string.JSON.parse(text, reviver)
โ Converts a JSON string back into a JavaScript object.
Basic Example:
let user = {
name: "John",
age: 30,
isAdmin: false,
courses: ["html", "css"],
spouse: null
};
let json = JSON.stringify(user);
console.log(json); // '{"name":"John","age":30,"isAdmin":false,"courses":["html","css"],"spouse":null}'
let parsed = JSON.parse(json);
console.log(parsed.name); // John
Key Details:
Strings & property names use double quotes.
Only JSON-supported types are serialized.
Functions,
undefined
, Symbols are skipped.Circular references cause
JSON.stringify
to throw.The
toJSON()
method is used if defined on the object.
๐น 2. Fill Any Gaps
Hidden & Advanced Mechanics:
JSON.stringify
internally walks the structure recursively and skips:Symbol keys
Properties with
undefined
, functions, or symbols as values
Prototype chain is ignored
toJSON()
is preferred over raw values (Date uses it)BigInt is not supported โ throws an error
Circular references throw
TypeError
Common Mistakes:
Forgetting that
Date
is converted to string, notDate
objectMisuse of
replacer
andreviver
โ must understand their recursive behaviorUsing single quotes or unquoted property names in manual JSON โ invalid
Browser Specifics:
- Some older browsers (IE<8) donโt support
JSON
natively (polyfill needed)
๐น 3. Challenge Me Deeply
๐ข Basic
Serialize a user object with name, age, and hobbies.
Serialize an array of 3 strings.
What happens when you stringify a function?
Parse a JSON string and access nested properties.
๐ก Intermediate
Serialize an object with nested objects and arrays.
Use
replacer
to exclude certain properties.Use
replacer
function to remove properties starting with_
.Convert a JSON date string into a real
Date
usingreviver
.
๐ด Advanced
Write a
toJSON()
for a custom class that returns a simplified version.Handle circular references manually using a
Set
in the replacer.
๐ฏ Bonus Brain-Twister
- Given a deeply nested object with some values as functions and
undefined
, write a custom serializer that skips them and logs the path of each skipped property.
๐น 4. Interview-Ready Questions
Conceptual:
What types are supported in JSON?
What is the difference between
undefined
andnull
in JSON?
Scenario-Based:
A backend sends a date string. How do you parse it as a Date object?
You need to exclude secret tokens from API logs. How?
Debugging:
JSON.parse(json).launchDate.getDate()
throws an error. Why?Your API fails because the payload has BigInt. How do you fix this?
Best Practices:
Always sanitize user input before
JSON.parse
Use
try/catch
around parsing untrusted JSON
Red Flags:
Relying on
JSON.stringify
for logging without replacer/spaceSending functions or BigInt in JSON API payloads
๐น 5. Real-World Usage
APIs: JSON is the de facto standard for REST APIs.
LocalStorage/SessionStorage: Store stringified data.
Redux DevTools: Serializes Redux store.
Database interactions: MongoDB drivers often use JSON for docs.
Frameworks/Libraries:
axios
,fetch
: auto-handle JSON parsingexpress.json()
middleware parses JSON bodies
Open-source Example:
Redux stores state as serializable JSON
ESLint config files can be in
.json
format
๐น 6. Remember Like a Pro
Mnemonic:
"S.P.A.R.T.A.": Stringify with
toJSON
, Parse withreviver
, Avoid circular refs, Remember double quotes, Trim functions/symbols, Avoid BigInt
Cheat Sheet:
JSON.stringify(obj, replacerFnOrArray, space); // serialize
JSON.parse(str, reviverFn); // deserialize
obj.toJSON = function() { return simplified; } // custom serialization
Common Trap Map:
Trap | Description |
undefined | Skipped in serialization |
function | Skipped |
Symbol | Skipped |
BigInt | Throws error |
circular refs | Throws TypeError |
๐น 7. Apply It in a Fun Way
Mini Project: JSON Config Editor
Build a web tool to:
Accept a config object from user
Show pretty-printed JSON view
Allow editing the JSON string
Parse and update back the object live
Highlight errors in JSON
Steps:
HTML form with textarea
JSON.stringify(obj, null, 2)
to display JSONOn edit, use
try/catch
andJSON.parse
to validateDisplay errors in a red box
On valid parse, reflect changes back into JS object
Extensions:
Syntax highlighting (use CodeMirror/Monaco)
Export to
.json
fileDark mode toggle
โ Bonus Insights
Open-Source Projects Using JSON Heavily:
npm
(package.json
)tsconfig.json
,babel.config.json
Firebase uses JSON for data exchange
Common Dev Mistakes:
Forgetting Date objects turn to strings
Misusing
replacer
andreviver
Over-relying on
JSON.stringify
for complex logs
Performance Tips:
Avoid unnecessary serialization on client side
Use
Buffer.from(JSON.stringify(obj))
for binary transport
Modern Alternative:
structuredClone()
is preferred for object copyingflatted
orcircular-json
libraries to handle circular references
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
