JavaScript JSON: Serialization, Parsing, Reviver Functions & Security

JSON (JavaScript Object Notation) is the universal standard data interchange format of the global software industry. Derived from JavaScript object literal syntax, JSON is strictly text-based and completely language-agnostic, easily parsed by Python, PHP, Java, C#, and Go.

Strict JSON Syntax Rules (vs. JavaScript Objects)

  • Keys MUST be enclosed in double quotes: "name": "Vikram" (Single quotes or unquoted keys are invalid!).
  • Strings MUST use double quotes: "title", never 'title'.
  • No Trailing Commas: [1, 2, 3,] is an invalid JSON syntax error.
  • Allowed Types: Object, Array, String, Number, Boolean, and null.

1. JSON.stringify(value, replacer, space) - Serialization

const student = {
    id: 101,
    name: "Vikram",
    enrolled: true,
    hobbies: ["chess", "coding"],
    secretToken: "xyz123" // Sensitive
};

// 1. Basic Serialization
const jsonString = JSON.stringify(student);
console.log(jsonString); // '{"id":101,"name":"Vikram","enrolled":true,"hobbies":["chess","coding"],"secretToken":"xyz123"}'

// 2. Formatted Pretty-Print with 2 spaces indentation:
const prettyJSON = JSON.stringify(student, null, 2);

// 3. Using Replacer Function to filter out sensitive keys:
const safeJSON = JSON.stringify(student, (key, val) => {
    if (key === "secretToken") return undefined; // Strips key!
    return val;
});
console.log(safeJSON); // secretToken is completely omitted!

2. JSON.parse(text, reviver) - Deserialization

const incomingPayload = '{"title":"BCA Syllabus","publishDate":"2026-11-05T08:00:00.000Z"}';

// Using a Reviver function to automatically reconstruct Date objects:
const parsedData = JSON.parse(incomingPayload, (key, value) => {
    if (key === "publishDate") return new Date(value);
    return value;
});

console.log(parsedData.publishDate instanceof Date); // true!

University Exam Corner (BCA Examination Notes)

Exam Trap: "What error occurs when running JSON.stringify() on an object with circular references?"

Answer: It throws TypeError: Converting circular structure to JSON.
Example: let a = {}; a.self = a; JSON.stringify(a);
The serializer enters an infinite loop trying to serialize 'a' inside itself and throws a TypeError.

Next Step

Congratulations on completing Tier 5: Asynchronous Programming & APIs! Now let us dive into the deepest engine internals of JavaScript. Proceed to Tier 6: JavaScript Execution Context & Hoisting Internals →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!