Lesson 45: Mastering JavaScript JSON methods with challenges!

manoj ymkmanoj ymk
4 min read

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, not Date object

  • Misuse of replacer and reviver โ€” must understand their recursive behavior

  • Using 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

  1. Serialize a user object with name, age, and hobbies.

  2. Serialize an array of 3 strings.

  3. What happens when you stringify a function?

  4. Parse a JSON string and access nested properties.

๐ŸŸก Intermediate

  1. Serialize an object with nested objects and arrays.

  2. Use replacer to exclude certain properties.

  3. Use replacer function to remove properties starting with _.

  4. Convert a JSON date string into a real Date using reviver.

๐Ÿ”ด Advanced

  1. Write a toJSON() for a custom class that returns a simplified version.

  2. Handle circular references manually using a Set in the replacer.

๐ŸŽฏ Bonus Brain-Twister

  1. 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 and null 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/space

  • Sending 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 parsing

  • express.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 with reviver, 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:

TrapDescription
undefinedSkipped in serialization
functionSkipped
SymbolSkipped
BigIntThrows error
circular refsThrows TypeError

๐Ÿ”น 7. Apply It in a Fun Way

Mini Project: JSON Config Editor
Build a web tool to:

  1. Accept a config object from user

  2. Show pretty-printed JSON view

  3. Allow editing the JSON string

  4. Parse and update back the object live

  5. Highlight errors in JSON

Steps:

  1. HTML form with textarea

  2. JSON.stringify(obj, null, 2) to display JSON

  3. On edit, use try/catch and JSON.parse to validate

  4. Display errors in a red box

  5. On valid parse, reflect changes back into JS object

Extensions:

  • Syntax highlighting (use CodeMirror/Monaco)

  • Export to .json file

  • Dark 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 and reviver

  • 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 copying

  • flatted or circular-json libraries to handle circular references

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk