Apps constantly move data around — saving to storage, sending it to servers, receiving it back. The lingua franca is JSON. This chapter ties together JSON, browser storage and talking to REST APIs — the practical plumbing behind almost every web feature.
JSON
JSON (JavaScript Object Notation) is a text format for data. Convert between JS values and JSON text with two functions:
const student = { name: "Aanya", tools: ["SQL", "Python"] };const text = JSON.stringify(student); // object → string (to send/store)// '{"name":"Aanya","tools":["SQL","Python"]}'JSON.stringify(student, null, 2); // pretty-printedconst back = JSON.parse(text); // string → object (when receiving)
Browser storage
localStorage persists small key/value string data in the browser across sessions (sessionStorage clears on tab close). Since it only stores strings, pair it with JSON:
// SavelocalStorage.setItem("prefs", JSON.stringify({ theme: "dark" }));// Load (with a fallback)const prefs = JSON.parse(localStorage.getItem("prefs") || "{}");localStorage.removeItem("prefs");localStorage.clear();
REST APIs with fetch
// GETconst res = await fetch("/api/students");const students = await res.json();// POST — createawait fetch("/api/students", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: "Rohan" }),});// PATCH updates, DELETE removes — same shape, different methodawait fetch("/api/students/42", { method: "DELETE" });
Headers & auth
Headers carry metadata: the content type, and authentication. A common pattern is a bearer token:
const res = await fetch("/api/me", {headers: {"Content-Type": "application/json","Authorization": `Bearer ${token}`,},});if (!res.ok) throw new Error(`HTTP ${res.status}`); // always check
Practice
Build a tiny preferences feature: read settings from localStorage (JSON), let the user change one, and save it back. Then write an async function that POSTs a new record to an API with the right headers and handles a non-OK response.
Key takeaways
- 01JSON.stringify serialises JS → text; JSON.parse deserialises text → JS (wrap parse in try/catch).
- 02localStorage persists string key/values across sessions; pair it with JSON.
- 03Never keep secrets/tokens in localStorage — it's readable by any script (XSS).
- 04fetch talks to REST APIs: GET/POST/PATCH/DELETE, JSON body, and always check response.ok.
- 05Headers carry Content-Type and auth (e.g. Authorization: Bearer <token>).
