JavaScript JSON and localStorage

JavaScript JSON (JavaScript Object Notation) is a text format for exchanging data. APIs send JSON, config files use it, and the browser's localStorage can only store strings, so JSON is how you save objects there.

JSON Syntax Rules

  • Keys must be in double quotes
  • Strings use double quotes only
  • Allowed values: string, number, boolean, null, array, object
  • No functions, undefined, comments or trailing commas

JSON.stringify: Object to Text

The third argument adds indentation for readable output.

const user = { name: "Ali", age: 25, skills: ["js", "css"], save: () => {} };
console.log(JSON.stringify(user));          // functions are dropped
console.log(JSON.stringify({ a: 1, b: 2 }, null, 2)); // pretty print
{"name":"Ali","age":25,"skills":["js","css"]}
{
  "a": 1,
  "b": 2
}

JSON.parse: Text to Object

An optional reviver function can convert values while parsing, such as turning date strings back into Date objects.

const text = '{"product":"Honey","price":11.5,"inStock":false}';
const obj = JSON.parse(text);
console.log(obj.product, obj.price * 2, obj.inStock);

const withDate = JSON.parse('{"created":"2026-01-05"}', (key, value) =>
  key === "created" ? new Date(value) : value
);
console.log(withDate.created.getFullYear());
Honey 23 false
2026

Saving Data with localStorage

localStorage keeps key-value strings in the browser even after it closes; sessionStorage clears when the tab closes. Stringify objects before saving and parse them when reading. Some sandboxed pages block storage, so wrap access in try...catch.

const settings = { theme: "dark", fontSize: 16 };
try {
  localStorage.setItem("settings", JSON.stringify(settings));
  const loaded = JSON.parse(localStorage.getItem("settings"));
  console.log(loaded.theme, loaded.fontSize);
  localStorage.removeItem("settings");
} catch (e) {
  console.log("Storage not available here:", e.name);
}
dark 16

Handling Invalid JSON

JSON.parse throws a SyntaxError on bad input, and getItem returns null for missing keys. Guard both when reading data you do not control.

Frequently asked questions

What is the difference between JSON and a JavaScript object?

JSON is a string format with strict rules. A JavaScript object is a live value in memory. JSON.parse and JSON.stringify convert between them.

How do I store an array or object in localStorage?

Convert it with JSON.stringify before setItem, and convert back with JSON.parse after getItem.

How much data can localStorage hold?

Usually about 5 MB per origin. For larger or structured data, use IndexedDB.