Kodokon kodokon.com

JSON, localStorage, and your first fetch

Serialize your data as JSON, persist it in the browser with localStorage, and retrieve remote data with fetch.

10 min · 3 questions

Open this lesson in Kodokon

JSON is the universal exchange format of the web: it's text whose syntax looks like JavaScript objects (keys in double quotes, no functions). Two methods are all you need: JSON.stringify turns a JavaScript value into a string, JSON.parse goes the other way.

JAVASCRIPT
const task = { title: "Review the lesson", done: false };

const json = JSON.stringify(task);
console.log(json);
// {"title":"Review the lesson","done":false}

const parsed = JSON.parse(json);
console.log(parsed.done); // false
A full round trip between a JavaScript object and a JSON string.

localStorage keeps data in the browser, even after the tab is closed. It's perfect for a chosen theme, a draft, or a task list. Since it only stores text, JSON acts as the bridge: serialize before setItem, deserialize after getItem.

JAVASCRIPT
const tasks = [
  { title: "Buy bread", done: false },
  { title: "Review the lesson", done: true }
];

localStorage.setItem("tasks", JSON.stringify(tasks));

const raw = localStorage.getItem("tasks");
const saved = raw ? JSON.parse(raw) : [];
console.log(saved.length); // 2
Saving then reading back a persistent task list.

The last building block: fetching data from a server. fetch sends an HTTP request and returns a promise. With async/await, the code reads from top to bottom: you wait for the response, check that it's valid, then wait for the JSON decoding, which is also asynchronous.

JAVASCRIPT
async function loadUsers() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
  );
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  const users = await response.json();
  console.log(users[0].name);
}

loadUsers();
A first complete network call with HTTP status checking.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does JSON.stringify do?
    • It converts a JSON string into a JavaScript object
    • It converts a JavaScript value into a JSON string
    • It validates the syntax of a JSON file
  2. What does localStorage.getItem return for a key that does not exist?
    • An empty string
    • undefined
    • null
    • An error is thrown
  3. Why write await response.json() rather than simply response.json()?
    • Because response.json() returns a promise
    • To convert the response into a string
    • To retry the request if it failed