JSON (JavaScript Object Notation) is the text format the web uses to exchange data. Servers send JSON to browsers, apps save settings as JSON, and localStorage can only store text, so objects go in as JSON. JavaScript has two built-in functions for it: JSON.stringify turns a value into JSON text, and JSON.parse turns JSON text back into a value. This lesson covers both, including the rules that trip people up and the extra arguments that let you filter and transform data.
In this lesson you will learn
- Converting values to JSON and back
- What JSON can and cannot store
- Pretty-printing with indentation
- Handling invalid JSON safely
- Replacers, revivers,
toJSONand deep copies
You should know objects and error handling.
stringify and parse
"use strict";
// JSON.stringify turns a value into JSON text
const course = {
title: "Web Development",
lessons: 32,
free: true,
tags: ["html", "css"],
teacher: null,
start: new Date(Date.UTC(2026, 0, 15)),
helper() { return "hi"; }, // functions are skipped
extra: undefined, // undefined is skipped
};
const text = JSON.stringify(course);
console.log(text);
console.log(typeof text, text.length, "characters");
// Pretty printing with indentation
console.log(JSON.stringify({ name: "Rina", marks: [90, 85] }, null, 2));
// JSON.parse turns JSON text back into a value
const back = JSON.parse(text);
console.log(back.title, back.tags[1], typeof back.start); // dates come back as strings
// Invalid JSON throws a SyntaxError: always catch it for outside data
for (const bad of ["{name: 'Rina'}", '{"a": 1,}', '']) {
try {
JSON.parse(bad);
} catch (e) {
console.log("Invalid JSON:", JSON.stringify(bad), "->", e.name);
}
}
Output
{"title":"Web Development","lessons":32,"free":true,"tags":["html","css"],"teacher":null,"start":"2026-01-15T00:00:00.000Z"}
string 124 characters
{
"name": "Rina",
"marks": [
90,
85
]
}
Web Development css string
Invalid JSON: "{name: 'Rina'}" -> SyntaxError
Invalid JSON: "{\"a\": 1,}" -> SyntaxError
Invalid JSON: "" -> SyntaxError
JSON.stringifyreturns a string. JSON supports strings, numbers, booleans,null, arrays and plain objects.- Other values are changed or dropped: functions and
undefinedproperties disappear, and aDatebecomes an ISO date string. - The third argument sets indentation.
JSON.stringify(value, null, 2)produces readable output for logs and files. JSON.parserebuilds objects and arrays. It does not know that a string was once a date, soback.startis just a string.- JSON is stricter than JavaScript: keys need double quotes, strings cannot use single quotes, and trailing commas are not allowed. Invalid text, including an empty string, throws a
SyntaxError, so wrapJSON.parseintry...catchwhenever the text comes from outside your program.
Replacers, Revivers and Deep Copies
"use strict";
// A replacer filters or changes values while stringifying
const user = { name: "Arif", email: "arif@example.com", password: "secret123", age: 21 };
console.log(JSON.stringify(user, ["name", "age"])); // keep only these keys
console.log(JSON.stringify(user, (key, value) =>
key === "password" ? undefined : value)); // drop one key
// toJSON lets an object decide its own JSON form
class Money {
constructor(taka) { this.taka = taka; }
toJSON() { return `${this.taka.toFixed(2)} BDT`; }
}
console.log(JSON.stringify({ fee: new Money(1500) }));
// A reviver rebuilds special values while parsing
const json = '{"title":"Exam","date":"2026-03-26T00:00:00.000Z","marks":[1,2]}';
const exam = JSON.parse(json, (key, value) =>
key === "date" ? new Date(value) : value);
console.log(exam.date instanceof Date, exam.date.getUTCFullYear());
// Deep copy: JSON round trip vs structuredClone
const original = { when: new Date(0), list: [1, [2, 3]], map: new Map([["a", 1]]) };
const viaJson = JSON.parse(JSON.stringify(original));
const viaClone = structuredClone(original);
original.list[1].push(4);
console.log("JSON copy:", typeof viaJson.when, viaJson.list, viaJson.map);
console.log("clone:", viaClone.when instanceof Date, viaClone.list, viaClone.map);
Output
{"name":"Arif","age":21}
{"name":"Arif","email":"arif@example.com","age":21}
{"fee":"1500.00 BDT"}
true 2026
JSON copy: string [ 1, [ 2, 3 ] ] {}
clone: true [ 1, [ 2, 3 ] ] Map(1) { 'a' => 1 }
- The second argument of
stringifyis a replacer. An array of keys keeps only those keys; a function sees every key and value and can returnundefinedto drop one. This is a simple way to keep a password out of logs. - If an object has a
toJSON()method,stringifyuses its result. Here aMoneyobject becomes a formatted string.Dateobjects work this way too. - The second argument of
parseis a reviver, called for every key and value. Turning thedatestring back into a realDateobject is its most common use. - A JSON round trip,
JSON.parse(JSON.stringify(obj)), makes a deep copy, but loses dates, maps and other special types.structuredClone(obj)makes a true deep copy that keeps them.
JavaScript Values in JSON
| JavaScript value | Result of JSON.stringify |
|---|---|
String, number, boolean, null | Kept as they are |
| Array, plain object | Kept, with their contents converted |
Date | ISO string, such as "2026-01-15T00:00:00.000Z" |
undefined, function, Symbol | Dropped from objects; null inside arrays |
NaN, Infinity | null |
Map, Set | {} (contents lost) |
BigInt | Throws a TypeError |
Common Mistakes
- Parsing without
try...catch, so one bad response crashes the page. - Calling
JSON.parseon something that is already an object; it is converted to the string"[object Object]"and fails. - Expecting dates to come back as
Dateobjects without a reviver. - Storing Maps and Sets as JSON directly. Convert them first, for example
[...map]orObject.fromEntries(map).
Practice Exercises
Exercise 1. Write safeParse(text, fallback) that returns the parsed value, or fallback if the text is not valid JSON.
Show answer
function safeParse(text, fallback) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
console.log(safeParse('{"a":1}', {}).a, safeParse("oops", [])); // 1 []
Exercise 2. Save a Set of tags to JSON and read it back as a Set.
Show answer
const tags = new Set(["js", "css"]);
const text = JSON.stringify([...tags]); // '["js","css"]'
const restored = new Set(JSON.parse(text));
Frequently Asked Questions
Is JSON the same as a JavaScript object?
No. JSON is a text format whose syntax is based on JavaScript object literals. A JavaScript object lives in memory and can hold functions, dates and other types; JSON is a string that can only describe plain data.
Does JSON allow comments?
No. Standard JSON has no comments, and JSON.parse rejects them. Some configuration files use extended formats such as JSONC, but those need special parsers.
Summary
JSON.stringifymakes text;JSON.parserebuilds values.- JSON stores plain data only; dates become strings and functions are dropped.
- Always catch errors when parsing outside data.
- Replacers, revivers and
toJSONcustomise conversion; usestructuredClonefor deep copies.
