SyntaxPilot
Courses/JavaScript/Lesson 19

JavaScript · Lesson 19 of 40 · 11 min

JSON

queued

These are the notes for JavaScript episode 19. An object lives in the computer's memory and vanishes when the program ends, but a file or a network message can only carry text. Writing an object into a file gives [object Object], and a home-made text format loses the types ("7" + 1 is "71"). You'll invent the fix, JSON: one strict text format that every language agrees on. You'll use JSON.stringify and JSON.parse, pretty print, learn JSON's strict rules and the real errors when they're broken, see what JSON drops (undefined, functions) or changes (NaN, Date), parse untrusted text safely with try/catch, hide a password with a replacer, and make a deep copy. Every output and error below is real Node.js 24 output (node main.js).

Builds on: objects (episode 8), destructuring and spread (12), try/catch (13), modules and node:fs (18).

The real-life idea: ordering over the phone

In a canteen, a real order sits on the table: two chai, one samosa, not paid. To send it to the kitchen by phone, you can't send the chai: only words travel. If everyone describes orders their own way ("two... or twelve?"), the kitchen gets it wrong. So canteens use a fixed order slip: item, quantity, paid. Anyone can write it, and anyone can read it back exactly.

Canteen JavaScript
The real order on the table an object in memory
The phone line a file or a network connection: only text travels
Everyone describing it differently home-made text formats
The fixed order slip JSON
Writing the slip JSON.stringify(obj) (object → text)
Reading the slip back JSON.parse(text) (text → object)

The problem: saving an object

Attempt 1: write the object into a file

const fs = require("node:fs");
const player = { name: "Asha", score: 7, badges: ["fast", "streak"] };
fs.writeFileSync("score.txt", `${player}`);
console.log(fs.readFileSync("score.txt", "utf8"));
[object Object]

When JavaScript turns an object into text by itself (in a template string, with String(obj) or + ""), it writes [object Object]. The name, the score and the badges are lost.

Attempt 2: a home-made format

const fs = require("node:fs");
const player = { name: "Asha", score: 7 };
fs.writeFileSync("score.txt", `name=${player.name},score=${player.score}`);
// ... the next day, read it back ...
const text = fs.readFileSync("score.txt", "utf8");
const [a, b] = text.split(",");
const back = { name: a.split("=")[1], score: b.split("=")[1] };
console.log(back);
console.log("Next score:", back.score + 1);
{ name: 'Asha', score: '7' }
Next score: 71

The score came back as the string "7", so + 1 joined text: "71". Text by itself can't tell the number 7 from the word "7". And this format breaks as soon as a name contains a comma or =, or the object has a list or a nested object; every other program would also need to learn your format.

Why: an object lives in memory; files and networks carry only text. We need one shared text format that keeps types and nesting, and that every program agrees on.

The fix: JSON

JSON (JavaScript Object Notation, said "jay-son") is a text format for data. It looks like a JavaScript object, but with strict rules:

{
  "name": "Asha",
  "score": 7,
  "pro": true,
  "badges": ["fast", "streak"],
  "coach": null,
  "stats": { "played": 12, "won": 9 }
}
JSON value Example
object { "key": value, ... }
array [ value, ... ]
string (double quotes only) "Asha"
number 7, 3.5, -2, 1e3
boolean true, false
null null

Not allowed in JSON (but fine in a JavaScript object): keys without quotes, single quotes, trailing commas, comments, undefined, functions, NaN/Infinity, dates and other special objects.

JSON.stringify and JSON.parse

JavaScript has a built-in JSON object with two methods:

  • JSON.stringify(value): value → JSON text (serializing)
  • JSON.parse(text): JSON text → value (parsing)
const fs = require("node:fs");
const player = { name: "Asha", score: 7, badges: ["fast", "streak"], pro: true };
const text = JSON.stringify(player);
console.log(text);
console.log(typeof text);
fs.writeFileSync("score.json", text);
// ... the next day ...
const back = JSON.parse(fs.readFileSync("score.json", "utf8"));
console.log(back);
console.log("Next score:", back.score + 1);
console.log(back.badges[1]);
{"name":"Asha","score":7,"badges":["fast","streak"],"pro":true}
string
{ name: 'Asha', score: 7, badges: [ 'fast', 'streak' ], pro: true }
Next score: 8
streak

The number stayed a number (8, not 71), the boolean stayed true, and the array came back as an array. back is a new object with the same data: back === player would be false.

object in memory ──JSON.stringify──▶ JSON text ──write / send──▶ file · network
                                                                      │
new object ◀──────JSON.parse─────── JSON text ◀──read / receive───────┘

Pretty printing

const order = { id: 101, items: ["Chai", "Samosa"], total: 35, paid: false };
console.log(JSON.stringify(order));
console.log(JSON.stringify(order, null, 2));
{"id":101,"items":["Chai","Samosa"],"total":35,"paid":false}
{
  "id": 101,
  "items": [
    "Chai",
    "Samosa"
  ],
  "total": 35,
  "paid": false
}

JSON.stringify(value, replacer, space): the third argument is the indent (a number of spaces, up to 10, or a string such as "\t"). The second, replacer, is a filter (below); pass null when you don't need it. Compact JSON is for machines; pretty JSON is for files people read (like package.json).

JSON's strict rules (and the real errors)

Single quotes

const text = "{'name': 'Asha', 'score': 7}";
const player = JSON.parse(text);
console.log(player);
{'name': 'Asha', 'score': 7}
 ^

SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
    at JSON.parse (<anonymous>)

Position 1 is the '. JSON keys and strings must use double quotes.

A trailing comma

const text = '{"name": "Asha", "score": 7,}';
console.log(JSON.parse(text));
{"name": "Asha", "score": 7,}
                            ^

SyntaxError: Expected double-quoted property name in JSON at position 28 (line 1 column 29)

After a comma JSON expects another key, but found }. Remove the last comma. The message always gives the position (and line/column), so you can find the mistake in a big file.

What JSON can't carry

const player = {
  name: "Asha",
  score: undefined,
  level: NaN,
  joined: new Date("2026-10-30T09:30:00Z"),
  greet() { return "hi"; },
};
const text = JSON.stringify(player);
console.log(text);
const back = JSON.parse(text);
console.log(typeof back.joined, back.greet);
{"name":"Asha","level":null,"joined":"2026-10-30T09:30:00.000Z"}
string undefined
In the object In the JSON After JSON.parse
score: undefined dropped missing
greet() {...} (a function) dropped missing
level: NaN (or Infinity) null null
joined: new Date(...) an ISO string "2026-10-30T09:30:00.000Z" a string, not a Date
undefined / function inside an array null (to keep positions) null
console.log(JSON.stringify([1, undefined, () => 2]));
[1,null,null]

JSON carries data, not behaviour. To get a Date back, rebuild it: new Date(back.joined), or use a reviver (practice 2). A Map or Set becomes {} (episode 21).

Rebuilding a date with a reviver

JSON.parse(text, reviver) calls reviver(key, value) for every value and uses what it returns:

const saved = '{"name":"Asha","joined":"2026-10-30T09:30:00.000Z"}';
const user = JSON.parse(saved, (key, value) =>
  key === "joined" ? new Date(value) : value);
console.log(user.joined instanceof Date, user.joined.getUTCFullYear());
true 2026

Parsing safely with try/catch

Text from outside (a file, a user, a server) can be broken: a half-written file after a power cut, an empty file, a typo. JSON.parse throws on bad input, so wrap it (episode 13):

function loadScore(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    console.log("Bad save file:", err.message);
    return { name: "Guest", score: 0 };
  }
}
console.log(loadScore('{"name":"Asha","score":7}'));
console.log(loadScore('{"name":"Asha","sco'));
console.log(loadScore(""));
{ name: 'Asha', score: 7 }
Bad save file: Unterminated string in JSON at position 19 (line 1 column 20)
{ name: 'Guest', score: 0 }
Bad save file: Unexpected end of JSON input
{ name: 'Guest', score: 0 }

JSON.stringify rarely throws; JSON.parse on outside text always needs a plan for failure.

The replacer: choosing what to send

const user = { name: "Asha", email: "asha@mail.com", password: "chai123", score: 7 };
console.log(JSON.stringify(user));
console.log(JSON.stringify(user, ["name", "score"]));
const safe = JSON.stringify(user, (key, value) =>
  key === "password" ? undefined : value);
console.log(safe);
{"name":"Asha","email":"asha@mail.com","password":"chai123","score":7}
{"name":"Asha","score":7}
{"name":"Asha","email":"asha@mail.com","score":7}
  • An array replacer keeps only those keys.
  • A function replacer is called for every key; returning undefined drops the key (the same drop rule as before, used on purpose).

A class can also decide how it's saved with a toJSON() method:

class Player {
  constructor(name, score) { this.name = name; this.score = score; this.password = "x"; }
  toJSON() { return { name: this.name, score: this.score }; }
}
console.log(JSON.stringify(new Player("Asha", 7)));
{"name":"Asha","score":7}

(That's how a Date becomes an ISO string: Date has a built-in toJSON.)

Deep copy with JSON

const a = { name: "Asha", badges: ["fast"] };
const b = { ...a };
b.badges.push("streak");
console.log(a.badges);
const c = JSON.parse(JSON.stringify(a));
c.badges.push("champion");
console.log(a.badges, c.badges);
[ 'fast', 'streak' ]
[ 'fast', 'streak' ] [ 'fast', 'streak', 'champion' ]

Spread makes a shallow copy: the top level is new, but a.badges and b.badges are the same array. A JSON round trip makes a deep copy: everything is new. It only works for JSON-safe data (dates become strings, functions vanish). Modern JavaScript has structuredClone(value), a deep copy that also keeps Date, Map and Set:

const copy = structuredClone({ d: new Date("2026-10-30T09:30:00Z"), list: [1, 2] });
console.log(copy.d instanceof Date);
true

Where you'll meet JSON

Place What it looks like
Web APIs a weather, payment or maps server replies with JSON text; await response.json() parses it (episode 27)
package.json every Node project's name, version, scripts and dependencies
Save files and settings games, editors (VS Code settings.json)
Databases MongoDB stores JSON-like documents; PostgreSQL has a json column type
Other languages Python json.loads, Java (Jackson/Gson), Go encoding/json all read the same text
require("./data.json") in CommonJS, Node reads and parses a .json file for you

Any JSON value can be the top level, not just an object:

console.log(JSON.stringify("chai"), JSON.stringify(42), JSON.parse("true"));
"chai" 42 true

Common mistakes (and what really happens)

You wrote What happens Why Fix
fs.writeFileSync(f, \${player}`)| the file contains[object Object]| objects don't become useful text by themselves |JSON.stringify(player)`
a home-made name=Asha,score=7 score comes back as '7'; + 1 gives 71 text loses types JSON
JSON.parse("{'name': 'Asha'}") SyntaxError: Expected property name or '}' in JSON at position 1 single quotes double quotes
JSON.parse('{"score": 7,}') SyntaxError: Expected double-quoted property name in JSON at position ... trailing comma remove it
JSON.parse("") SyntaxError: Unexpected end of JSON input empty or cut-off text try/catch with a fallback
JSON.parse('{"name":"Asha","sco') SyntaxError: Unterminated string in JSON at position 19 cut-off text try/catch
back.joined.getFullYear() TypeError: back.joined.getFullYear is not a function a Date comes back as a string new Date(back.joined) or a reviver
JSON.stringify(user) before sending the password is sent too everything is included replacer or toJSON
{ ...a } to copy nested data changes to inner arrays show in both spread is shallow structuredClone(a) or a JSON round trip

Mini project: a high-score table that survives restarts

Keep the top 3 scores in scores.json, with the date of each score; start fresh if the file is missing or broken.

const fs = require("node:fs");
const FILE = "scores.json";

function loadScores() {
  try {
    return JSON.parse(fs.readFileSync(FILE, "utf8"));
  } catch (err) {
    console.log("Starting fresh:", err.message);
    return [];
  }
}

function saveScore(name, score) {
  const scores = loadScores();
  scores.push({ name, score, at: new Date().toISOString() });
  scores.sort((a, b) => b.score - a.score);
  fs.writeFileSync(FILE, JSON.stringify(scores.slice(0, 3), null, 2));
}

saveScore("Asha", 7);
saveScore("Ravi", 9);
saveScore("Meena", 5);
saveScore("Kabir", 8);
for (const s of loadScores()) {
  const when = new Date(s.at);
  console.log(`${s.name.padEnd(6)} ${s.score}  (${when.getFullYear()})`);
}

First run (no file yet):

Starting fresh: ENOENT: no such file or directory, open 'scores.json'
Ravi   9  (2026)
Kabir  8  (2026)
Asha   7  (2026)

scores.json now starts like this (your times will differ):

[
  {
    "name": "Ravi",
    "score": 9,
    "at": "2026-10-30T20:49:55.762Z"
  },

Run it again and the old scores are still there. The file is readable, a missing file doesn't crash the game, and the date is rebuilt with new Date.

Practice

  1. Stringify a settings object { theme: "dark", fontSize: 16, sound: true, recent: ["ep18", "ep19"] } with 2-space indent, parse it back, and print the length of the text, fontSize + 2 and the number of recent items.
  2. Parse '{"name":"Asha","joined":"2026-10-30T09:30:00.000Z"}' so that joined is a real Date.
  3. Write isValidJSON(text) that returns true or false without crashing. Test '{"a":1}', "{a:1}", "[1,2,]" and "42".
  4. Give a Player class a toJSON method so its password is never saved.
Solutions

1.

const settings = { theme: "dark", fontSize: 16, sound: true, recent: ["ep18", "ep19"] };
const text = JSON.stringify(settings, null, 2);
const back = JSON.parse(text);
console.log(text.length, back.fontSize + 2, back.recent.length);
98 18 2

2.

const saved = '{"name":"Asha","joined":"2026-10-30T09:30:00.000Z"}';
const user = JSON.parse(saved, (key, value) =>
  key === "joined" ? new Date(value) : value);
console.log(user.joined instanceof Date, user.joined.getUTCFullYear());
true 2026

3.

function isValidJSON(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}
console.log(isValidJSON('{"a":1}'), isValidJSON("{a:1}"), isValidJSON("[1,2,]"), isValidJSON("42"));
true false false true

"42" is valid JSON: any JSON value can be the top level.

  1. See the Player example with toJSON() above: it prints {"name":"Asha","score":7}.

Quick quiz

What does this print?

const p = { a: 1, b: undefined, c: [2, "3"], d: () => 4 };
console.log(JSON.stringify(p));
  • A. {"a":1,"c":[2,"3"]}
  • B. {"a":1,"b":null,"c":[2,3]}
  • C. {"a":1,"b":undefined,"c":[2,"3"],"d":4}
  • D. SyntaxError
Answer

A. In an object, undefined values and functions are dropped. The string "3" stays a string: JSON keeps types exactly.

Interview questions

  • What is JSON, and why is it used for APIs and config files?
  • What's the difference between a JavaScript object and JSON?
  • What do JSON.stringify and JSON.parse do? What are serializing and parsing?
  • What happens to undefined, functions, NaN and Date objects in JSON.stringify?
  • Why must you wrap JSON.parse in try/catch for outside data?
  • What are the second and third arguments of JSON.stringify?
  • What is a reviver in JSON.parse?
  • What does toJSON do?
  • Shallow copy vs deep copy: how do spread, a JSON round trip and structuredClone differ?
  • Why is JSON.stringify(new Map([[1, 2]])) equal to "{}"?

Glossary

Term Meaning Example
JSON JavaScript Object Notation: a strict text format for data, read by every language {"name":"Asha","score":7}
Serialize turn data in memory into text (or bytes) to store or send JSON.stringify(player)
Parse read text and build the data it describes JSON.parse(text)
JSON.stringify(value, replacer, space) value → JSON text JSON.stringify(o, null, 2)
JSON.parse(text, reviver) JSON text → value; throws SyntaxError on bad text JSON.parse('{"a":1}')
Round trip stringify then parse, getting equal data back save and load a score
Pretty print JSON with line breaks and indentation JSON.stringify(o, null, 2)
Replacer a filter for stringify: an array of keys, or a function ["name", "score"]
Reviver a function for parse that can transform each value turn an ISO string into a Date
toJSON() a method that decides how an object is stringified Date has one; your classes can too
ISO date string the standard text form of a date and time, in UTC "2026-10-30T09:30:00.000Z"
null JSON's "no value"; NaN and Infinity become null "coach": null
Shallow copy a copy whose nested objects are shared with the original { ...a }
Deep copy a copy where every nested object is new too structuredClone(a)
structuredClone a built-in deep copy that also keeps Date, Map, Set structuredClone(obj)
API a service your program talks to; on the web it usually replies in JSON a weather API
package.json the JSON file describing a Node project { "name": "quiz", "type": "module" }
[object Object] what an object becomes when turned into text without JSON `${player}`

Summary

  • Objects live in memory; files and networks carry text. ${obj} gives [object Object], and home-made formats lose types.
  • JSON is one strict text format everyone agrees on: double-quoted keys and strings, numbers, true/false, null, arrays, objects.
  • JSON.stringify(obj) → text; JSON.parse(text) → a new object. JSON.stringify(obj, null, 2) pretty prints.
  • No single quotes, no trailing commas, no comments: the SyntaxError gives the exact position.
  • undefined and functions are dropped, NaN → null, a Date → an ISO string (rebuild it with new Date or a reviver).
  • Wrap JSON.parse in try/catch for outside text. Use a replacer or toJSON to hide fields. JSON round trip = deep copy (or structuredClone).

Next episode: Date and Math. Splitting a ₹100 bill three ways prints 33.333333333333336, a lucky draw needs whole random numbers, and "delivery in 7 days" needs a real calendar.