Storing Complex Data with JSON
You'll learn how to store objects and arrays in localStorage/sessionStorage using JSON serialization and deserialization.
The Problem: Storage Only Holds Strings
Web Storage (localStorage and sessionStorage) can only store text—strings. But what if you want to save an array of products, a user profile object, or nested data? If you try to store an object directly, you'll get "[object Object]" instead of your actual data!
The Solution: JSON as a Translator
Think of JSON (JavaScript Object Notation) as a universal translator. It converts complex JavaScript data into a string format that can be stored, then converts it back when you need it.
Serializing (Object → String):
const user = {
name: "Alice",
age: 30,
preferences: ["dark mode", "notifications"]
};
// Convert object to JSON string
const jsonString = JSON.stringify(user);
localStorage.setItem("user", jsonString);
// Stored as: '{"name":"Alice","age":30,"preferences":["dark mode","notifications"]}'
Deserializing (String → Object):
// Retrieve the JSON string
const retrieved = localStorage.getItem("user");
// Convert back to JavaScript object
const userObject = JSON.parse(retrieved);
console.log(userObject.name); // "Alice"
console.log(userObject.preferences); // ["dark mode", "notifications"]
A Complete Pattern
// Saving complex data
const cart = [
{ id: 1, product: "Laptop", price: 999 },
{ id: 2, product: "Mouse", price: 25 }
];
localStorage.setItem("cart", JSON.stringify(cart));
// Loading complex data
const loadedCart = JSON.parse(localStorage.getItem("cart"));
console.log(loadedCart[0].product); // "Laptop"
Key Takeaway: Use JSON.stringify() to convert objects/arrays into strings before storing, and JSON.parse() to convert them back after retrieving—this lets you store any serializable JavaScript data structure in Web Storage.