JavaScript course menu
JSON in JavaScript: JSON.stringify, JSON.parse and Common Pitfalls
Learn JSON (JavaScript Object Notation): its syntax rules, converting objects to JSON with JSON.stringify (with indentation, replacers and toJSON), parsing JSON with JSON.parse safely, what JSON cannot store, and using JSON with APIs and localStorage.
On this page
JSON (JavaScript Object Notation) is a text format for data. It looks like JavaScript objects and arrays, but it is just a string, which makes it easy to send over a network or save to a file. Nearly every web API sends and receives JSON, in every programming language.
What JSON looks like#
{
"name": "Asha Rao",
"age": 21,
"isStudent": true,
"skills": ["HTML", "CSS", "JavaScript"],
"address": { "city": "Pune", "pin": "411001" },
"phone": null
}JSON is stricter than JavaScript:
JSON.stringify: object to text#
const user = { name: "Asha", age: 21, skills: ["HTML", "CSS"] };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);{"name":"Asha","age":21,"skills":["HTML","CSS"]}
stringPretty printing#
The third argument adds indentation, which makes JSON readable for people and logs:
const user = { name: "Asha", skills: ["HTML", "CSS"] };
console.log(JSON.stringify(user, null, 2));{
"name": "Asha",
"skills": [
"HTML",
"CSS"
]
}Choosing what to include#
The second argument, the replacer, can be an array of keys to keep, or a function:
const account = { username: "asha", password: "secret123", plan: "pro" };
console.log(JSON.stringify(account, ["username", "plan"]));
console.log(JSON.stringify(account, (key, value) => (key === "password" ? undefined : value)));{"username":"asha","plan":"pro"}
{"username":"asha","plan":"pro"}JSON.parse: text to object#
const text = '{"product":"Pen","price":20,"tags":["blue","gel"]}';
const data = JSON.parse(text);
console.log(data.product, data.price);
console.log(data.tags[1]);Pen 20
gelParse safely#
Invalid JSON throws a SyntaxError. Data from outside your program (an API, a file, localStorage) can be broken, so wrap parsing in try...catch:
function safeParse(text, fallback) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
console.log(safeParse('{"ok": true}', {}));
console.log(safeParse("{name: 'Asha'}", {}));
console.log(safeParse("", []));{ ok: true }
{}
[]What JSON loses#
JSON only has strings, numbers, booleans, null, arrays and objects. Other values change or disappear:
const event = {
title: "Workshop",
date: new Date("2026-11-14T10:00:00Z"),
notes: undefined,
onClick() {},
attendees: new Set(["Asha"]),
score: NaN,
};
console.log(JSON.stringify(event));{"title":"Workshop","date":"2026-11-14T10:00:00.000Z","attendees":{},"score":null}Datebecomes an ISO string;JSON.parsegives you back a string, not a Date.undefinedvalues and functions are dropped.SetandMapbecome{}. Convert them first:[...set]orObject.fromEntries(map).NaNandInfinitybecomenull.
Restoring dates with a reviver#
JSON.parse takes an optional reviver function to convert values back:
const text = '{"title":"Workshop","date":"2026-11-14T10:00:00.000Z"}';
const event = JSON.parse(text, (key, value) => (key === "date" ? new Date(value) : value));
console.log(event.date instanceof Date);
console.log(event.date.getUTCFullYear());true
2026Deep copies#
JSON.parse(JSON.stringify(obj)) was the classic way to deep-copy data, but it loses dates, undefined, Maps and so on. Use structuredClone(obj) instead.
Where you will use JSON#
- APIs:
fetchresponses are usually JSON, read withresponse.json()(Fetching Data). - Saving in the browser:
localStorageonly stores strings, so objects are saved withJSON.stringify(localStorage). - Configuration files:
package.json,tsconfig.jsonand many others.
Practice#
Practice exercise
Convert this array of tasks to pretty-printed JSON with 2-space indentation, but leave out the internalId field. Then parse the JSON back and print how many tasks are done.
const tasks = [
{ internalId: "x1", title: "Learn JSON", done: true },
{ internalId: "x2", title: "Practise fetch", done: false },
];Show solution
const tasks = [
{ internalId: "x1", title: "Learn JSON", done: true },
{ internalId: "x2", title: "Practise fetch", done: false },
];
const json = JSON.stringify(tasks, ["title", "done"], 2);
console.log(json);
const parsed = JSON.parse(json);
console.log(parsed.filter((t) => t.done).length);[
{
"title": "Learn JSON",
"done": true
},
{
"title": "Practise fetch",
"done": false
}
]
1Key takeaway#
Finished this lesson?