JavaScript JSON and Local Storage

JSON and Local Storage are two essential tools for data handling in JavaScript. JSON provides a standard format for exchanging data, while Local Storage allows saving data in the browser so it persists even after the page is closed.

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight, text-based format for representing structured data. JSON is used to send and receive data between a browser and a server, and between different applications.

JSON looks very similar to JavaScript objects, but it follows stricter rules:

  • All keys must be in double quotes
  • String values must use double quotes (not single quotes)
  • No trailing commas allowed
  • Functions, undefined, and symbols are not valid JSON values

Valid JSON Example

{
  "name": "Aditya",
  "age": 28,
  "isStudent": false,
  "courses": ["JavaScript", "Python", "SQL"],
  "address": {
    "city": "Pune",
    "pin": "411001"
  }
}

JSON.stringify() — Convert Object to JSON String

JavaScript objects cannot be stored or transmitted directly. JSON.stringify() converts an object into a JSON-formatted string.

let student = {
  name: "Reena",
  age: 22,
  courses: ["Math", "Science"]
};

let jsonString = JSON.stringify(student);
console.log(jsonString);
// '{"name":"Reena","age":22,"courses":["Math","Science"]}'
console.log(typeof jsonString);  // string

Formatting JSON Output (Pretty Print)

let formatted = JSON.stringify(student, null, 2);
console.log(formatted);
// {
//   "name": "Reena",
//   "age": 22,
//   "courses": [
//     "Math",
//     "Science"
//   ]
// }

JSON.parse() — Convert JSON String Back to Object

JSON.parse() takes a JSON string and converts it back into a usable JavaScript object.

let jsonString = '{"name":"Reena","age":22}';

let student = JSON.parse(jsonString);
console.log(student.name);  // Reena
console.log(student.age);   // 22

Handling JSON Parse Errors

try {
  let obj = JSON.parse("{invalid json}");
} catch (error) {
  console.log("Invalid JSON:", error.message);
}

Deep Copying an Object with JSON

A quick way to deeply copy an object (all nested levels) is to stringify and then parse it.

let original = { name: "Ravi", scores: [90, 85, 78] };
let deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.scores.push(100);

console.log(original.scores);  // [90, 85, 78] — unchanged
console.log(deepCopy.scores);  // [90, 85, 78, 100]

What is Local Storage?

Local Storage is a browser-based storage system that allows data to be saved as key-value string pairs. Data stored here persists even after the browser is closed or the page is refreshed — unlike regular JavaScript variables which are reset on page reload.

Local Storage is useful for:

  • Saving user preferences (dark mode, language)
  • Storing shopping cart items
  • Remembering login session details
  • Caching API response data locally

Local Storage Limits

  • Can store up to 5–10 MB per domain (varies by browser)
  • Data is specific to each domain
  • Stores only strings — objects must be converted with JSON
  • Not suitable for sensitive data (not encrypted)

Local Storage Methods

setItem() — Store Data

localStorage.setItem("username", "Priya");
localStorage.setItem("theme", "dark");

getItem() — Retrieve Data

let name = localStorage.getItem("username");
console.log(name);  // Priya

// Returns null if the key doesn't exist
let missing = localStorage.getItem("nonexistent");
console.log(missing);  // null

removeItem() — Delete a Specific Key

localStorage.removeItem("theme");

clear() — Delete All Stored Data

localStorage.clear();

key() — Get Key Name by Index

localStorage.setItem("color", "blue");
localStorage.setItem("size", "medium");

console.log(localStorage.key(0));  // "color" (or "size" — order not guaranteed)

length — Number of Stored Items

console.log(localStorage.length);  // 2

Storing Objects in Local Storage

Local Storage only stores strings. To store objects or arrays, convert them using JSON.stringify() before storing, and JSON.parse() after retrieving.

// Store an object
let user = { name: "Ankit", role: "admin", lastLogin: "2026-03-08" };
localStorage.setItem("currentUser", JSON.stringify(user));

// Retrieve and parse
let storedUser = JSON.parse(localStorage.getItem("currentUser"));
console.log(storedUser.name);  // Ankit
console.log(storedUser.role);  // admin
// Store an array
let cart = ["Laptop", "Mouse", "Keyboard"];
localStorage.setItem("cart", JSON.stringify(cart));

// Retrieve the array
let savedCart = JSON.parse(localStorage.getItem("cart"));
console.log(savedCart);  // ["Laptop", "Mouse", "Keyboard"]

Session Storage

Session Storage works exactly like Local Storage, but data is cleared when the browser tab is closed. It is useful for temporary data that should not persist beyond the current session.

// Store temporarily for this tab session
sessionStorage.setItem("searchQuery", "JavaScript tutorial");
let query = sessionStorage.getItem("searchQuery");
console.log(query);  // JavaScript tutorial
// Cleared automatically when the tab is closed

Local Storage vs Session Storage

FeatureLocal StorageSession Storage
PersistenceUntil manually clearedUntil tab is closed
ScopeAll tabs in the browserCurrent tab only
Max Size~5-10 MB~5 MB
Use CaseLong-term preferences, cartForm data, temporary session

Practical Example — Theme Preference Saver

// Save theme preference
function saveTheme(theme) {
  localStorage.setItem("userTheme", theme);
  console.log("Theme saved:", theme);
}

// Load saved theme on page load
function loadTheme() {
  let savedTheme = localStorage.getItem("userTheme");
  if (savedTheme) {
    document.body.className = savedTheme;
    console.log("Loaded theme:", savedTheme);
  } else {
    console.log("No saved theme. Using default.");
  }
}

// Usage
saveTheme("dark-mode");
loadTheme();  // Loaded theme: dark-mode

Practical Example — To-Do List with Persistence

// Save to-do items
function saveTasks(tasks) {
  localStorage.setItem("tasks", JSON.stringify(tasks));
}

// Load to-do items
function loadTasks() {
  let stored = localStorage.getItem("tasks");
  return stored ? JSON.parse(stored) : [];
}

// Add a task
let tasks = loadTasks();
tasks.push("Buy groceries");
tasks.push("Study JavaScript");
saveTasks(tasks);

// Retrieve and show
let allTasks = loadTasks();
allTasks.forEach((task, i) => {
  console.log(`${i + 1}. ${task}`);
});

Key Points to Remember

  • JSON is a text format for representing structured data — used for APIs and data exchange
  • JSON.stringify() converts a JavaScript object to a JSON string
  • JSON.parse() converts a JSON string back to a JavaScript object
  • Always wrap JSON.parse() in a try/catch block to handle invalid JSON
  • Local Storage stores data permanently (until cleared) as key-value string pairs
  • Session Storage stores data only for the duration of the browser tab session
  • Store objects/arrays in Local Storage using JSON — stringify before set, parse after get
  • Local Storage is not secure — never store passwords or sensitive data in it

Leave a Comment

Your email address will not be published. Required fields are marked *