JSON
JSON is the data format of the web: APIs send it, apps store it, config files use it. Its syntax comes from JavaScript object literals, with a few strict rules.
Object to JSON text: stringify
JavaScript
const user = { name: "Asha", age: 21, skills: ["JS", "Python"], member: true };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);
console.log(JSON.stringify(user, null, 2)); // pretty-printed with 2-space indentsJSON text to object: parse
JavaScript
const response = '{"city":"Osaka","temp":21.5,"forecast":["sun","rain"]}';
const weather = JSON.parse(response);
console.log(weather.city, weather.temp);
console.log(weather.forecast[1]);JSON's rules
JSON is stricter than JavaScript:
- keys must be in double quotes,
- strings must use double quotes,
- no trailing commas, no comments,
- values can only be strings, numbers,
true,false,null, arrays and objects.
JavaScript
try {
JSON.parse("{name: 'Asha'}"); // unquoted key, single quotes
} catch (err) {
console.log("Invalid JSON:", err.message);
}Always wrap JSON.parse in try/catch when the text comes from outside your program.
What stringify leaves out
JavaScript
const data = {
title: "Report",
created: new Date(2026, 0, 15),
helper: () => "functions are skipped",
nothing: undefined,
empty: null,
};
console.log(JSON.stringify(data));Functions and undefined disappear, and dates become ISO strings (parse them back with new Date(text)).
Deep copies
A JSON round trip makes an independent copy of plain data; the modern built-in structuredClone does it better (it keeps dates, Maps and Sets):
JavaScript
const original = { name: "Mei", scores: [80, 90] };
const copy = structuredClone(original);
copy.scores.push(100);
console.log(original.scores, copy.scores);Saving to the browser
localStorage only stores strings, so JSON is how objects are saved there. It's exactly how CodeMIRAI remembers your progress:
JavaScript
localStorage.setItem("settings", JSON.stringify({ theme: "dark" }));
const settings = JSON.parse(localStorage.getItem("settings"));Finished this lesson?Mark it complete to earn +20 XP and move your progress on.