Skip to content

Lesson 20 of 50JavaScript in depth

JSON and Browser Storage

Write valid JSON, convert data with JSON.stringify and JSON.parse, fix the common errors, and save data safely in localStorage and sessionStorage.

15 min read0/4 questions

Sooner or later your data has to leave JavaScript. It gets sent to a server, received from an API, written to a file, or saved in the browser so it is still there after a refresh. None of those places understand JavaScript objects directly. They understand text. JSON is the text format almost everyone agreed on for this job, and browser storage is the simplest place to keep a little of it on the user's device. This lesson covers the JSON rules, the two functions that convert to and from it, the errors you will meet, and how to use localStorage without losing data or leaking secrets.

What JSON is

JSON (JavaScript Object Notation, said "jay-son") is a text format for structured data. It looks almost exactly like JavaScript objects and arrays, which is why it is easy to read, but it is stricter. Here is a recipe as JSON:

{
  "title": "Pancakes",
  "servings": 4,
  "vegetarian": true,
  "rating": null,
  "ingredients": ["flour", "milk", "eggs"],
  "time": { "prep": 10, "cook": 15 }
}

JSON can hold six kinds of value: strings, numbers, booleans (true, false), null, arrays and objects. Nothing else. The rules that trip people up:

  • Keys must be in double quotes: "title", never title.
  • Strings use double quotes only. Single quotes are not allowed.
  • No trailing commas after the last item.
  • No comments.
  • No undefined, no functions, no NaN or Infinity, no dates (dates travel as strings).

Almost every web API speaks JSON, and so do configuration files like package.json. Python, Go, Java and every other popular language can read and write it, which is the whole point: it is a shared language between programs.

Quick checkPick all that apply
Which of these is valid JSON? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

JSON.stringify and JSON.parse

Two built-in functions do the conversion:

  • JSON.stringify(value) turns a JavaScript value into a JSON string. This is called serialising.
  • JSON.parse(text) turns a JSON string back into a JavaScript value. This is parsing, or deserialising.
JavaScript
const recipe = { title: "Pancakes", servings: 4, tags: ["breakfast", "sweet"], notes: undefined, // dropped cook() {}, // dropped rating: NaN, // becomes null saved: new Date("2026-03-01T09:30:00Z"), // becomes a string}; const text = JSON.stringify(recipe);console.log(typeof text);console.log(text); // Pretty print: the third argument is the indentconsole.log(JSON.stringify({ title: "Pancakes", servings: 4 }, null, 2)); const back = JSON.parse(text);console.log(back.title, back.tags.length);console.log(typeof back.saved, back.saved); // a string, not a Dateconsole.log(new Date(back.saved).getUTCHours()); // convert it back yourself
Output
Press Run (⌘ Enter) to see what happens.

Look closely at what did not survive the round trip. JSON.stringify silently drops properties whose value is undefined or a function, turns NaN and Infinity into null, and turns a Date into an ISO date string. When you parse it again, the date stays a string; JSON has no way to say "this is a date". Maps and Sets come out as {}, because they keep their data outside normal properties. Convert them first with Object.fromEntries(map) or [...set].

The optional second argument to stringify is a replacer. Pass an array of key names to keep only those (JSON.stringify(user, ["id", "name"])), which is a handy way to avoid sending fields you did not mean to.

Predict the outputJavaScript

What does this print?

const user = { name: "Sam", age: undefined, admin: false };
console.log(JSON.stringify(user));
Need a nudge? Hints walk you through it.

JSON over the network

You will meet these two functions most often around network requests. When you send data to a server, you JSON.stringify it into the request body and add a Content-Type: application/json header so the server knows how to read it. When a response comes back, await response.json() reads the body and runs JSON.parse for you, so you get a normal object or array straight away. The async and fetch lesson walks through both directions. The important idea for now is that a network is a pipe for text: everything you send is serialised on one side and parsed on the other, which is exactly why the rules above matter.

Common JSON errors

JSON.parse throws a SyntaxError when the text is not valid JSON. The messages vary between browsers, but these situations cause most of them:

What you seeWhat usually happened
Unexpected token '<', "<!DOCTYPE "... is not valid JSONThe server sent an HTML page (often a 404 or error page), not JSON
"undefined" is not valid JSONYou parsed undefined, usually a missing value read from storage or a property that does not exist
"[object Object]" is not valid JSONYou parsed something that was already an object. It became the string "[object Object]"
Expected property name or '}'Hand-written JSON with single quotes, unquoted keys or a trailing comma

Because parsing can fail, wrap it whenever the text comes from outside your code: from storage, a file, a URL or a network response.

JavaScript
function safeParse(text, fallback) { try { return JSON.parse(text); } catch (err) { console.log("Could not parse:", err.name); return fallback; }} console.log(safeParse('{"theme":"dark"}', {}));console.log(safeParse("{theme: 'dark'}", {}));console.log(safeParse("<!DOCTYPE html><html>", {}));console.log(safeParse(null, {})); // null is valid JSON text once converted to "null" // The double-stringify bug: a string of JSON stringified againconst once = JSON.stringify({ a: 1 });const twice = JSON.stringify(once);console.log(twice);console.log(typeof JSON.parse(twice)); // still a string, not an object
Output
Press Run (⌘ Enter) to see what happens.

The last example is a bug you will meet in real code: something was stringified twice, so parsing it once gives you back a string of JSON, full of backslashes, instead of an object. If you see \" all over your data, look for the extra stringify.

localStorage and sessionStorage

Browsers give every website a small key and value store that survives page reloads. There are two versions with the same methods:

  • localStorage keeps data until your code or the user clears it, even after the browser is closed.
  • sessionStorage keeps data only for the current tab. Close the tab and it is gone. Each tab has its own copy.

Both are scoped to the origin (the protocol, domain and port, like https://example.com), so one site cannot read another site's storage. The methods are simple: setItem(key, value), getItem(key) (which returns null for a missing key), removeItem(key) and clear(). Most browsers allow around 5 MB per origin, and every call is synchronous, so it pauses your code while it reads or writes. That is fine for settings and small lists, not for big data.

The one rule that causes most bugs: storage only holds strings. Give it anything else and it converts the value with String(), which turns an object into the useless text "[object Object]". So objects go in with JSON.stringify and come out with JSON.parse.

Saving a to-do list across a reload
Your codeJSONlocalStoragestringify(todos)'[{"text":"Buy milk"}]'setItem("todos", text)getItem("todos")the string, or nullparse(text)

The array of objects becomes one JSON string.

1/6

Here is a pair of helpers worth copying into any project. The code windows on this site run in a background worker that has no localStorage, so the example begins with a tiny stand-in that has the same methods. In a real page you would delete the stand-in and the helpers would use the browser's own localStorage.

JavaScript
// Stand-in for window.localStorage (delete this in a real page)const store = new Map();const localStorage = { setItem: (key, value) => store.set(key, String(value)), getItem: (key) => (store.has(key) ? store.get(key) : null), removeItem: (key) => store.delete(key),}; function save(key, value) { localStorage.setItem(key, JSON.stringify(value));} function load(key, fallback) { const text = localStorage.getItem(key); if (text === null) return fallback; // never saved try { return JSON.parse(text); } catch { return fallback; // corrupted or from an old version }} // The classic mistake: storing an object without stringifylocalStorage.setItem("broken", { theme: "dark" });console.log(localStorage.getItem("broken")); save("settings", { theme: "dark", fontSize: 16 });save("todos", [{ text: "Buy milk", done: false }]); const settings = load("settings", { theme: "light", fontSize: 14 });console.log(settings.theme, settings.fontSize);console.log(load("todos", []).length);console.log(load("missing", []));
Output
Press Run (⌘ Enter) to see what happens.

Two more habits pay off as an app grows. Prefix your keys (recipeApp:settings) so they do not collide with other code on the same origin. And when the shape of saved data changes, store a version number with it, so load can recognise an old format and upgrade it instead of crashing.

Quick check
A page saves settings with localStorage.setItem("settings", settings) where settings is an object. What does getItem("settings") return after a reload?
Need a nudge? A hint rules out a wrong answer.

What not to store

Anything in localStorage can be read by any JavaScript running on your page. That includes your own code, every third-party script you load (analytics, chat widgets, ads), and an attacker's script if your site has an XSS hole (the strings lesson explains how that happens). It is also stored as plain text on the device, visible to anyone who opens DevTools on that computer.

So never store:

  • Passwords, ever.
  • Secret API keys. Anything shipped to the browser is public anyway; secret keys belong on your server.
  • Long-lived login tokens, if you can avoid it. The safer default for login sessions is a cookie the server sets with the HttpOnly flag, which JavaScript cannot read at all, plus Secure and SameSite.
  • Sensitive personal data, such as health or payment details.

Good things to store: the theme, a collapsed sidebar, the last selected tab, a draft that has not been sent yet, a shopping cart for a logged-out visitor. If losing it or someone seeing it would not hurt, storage is a fine home.

Match the pairs0/4 matched

Pick the best place for each piece of data.

Choose an item, then its match on the other side.
Key terms
JSON
A strict text format for data: strings, numbers, booleans, null, arrays and objects, with double-quoted keys.
serialise
Turn a value into text for storing or sending. JSON.stringify does this.
parse
Turn text back into a value. JSON.parse does this and throws a SyntaxError on invalid JSON.
localStorage
A per-origin, string-only key and value store that survives reloads and browser restarts.
sessionStorage
Like localStorage, but scoped to one tab and cleared when the tab closes.
origin
Protocol, domain and port together. Storage is shared within an origin and separate between origins.
HttpOnly cookie
A cookie JavaScript cannot read, which makes it the safer home for login sessions.