Storing Objects with JSON
Serialize objects to store and retrieve them.
Storage Holds Only Strings
Web Storage stores strings, so you cannot save an object directly. Storing one yields the useless text "[object Object]". The fix is JSON.
localStorage.setItem("user", { name: "Ada" });
console.log(localStorage.getItem("user")); // "[object Object]"Serialize With JSON.stringify
Convert an object to a JSON string with JSON.stringify before storing it.
const user = { name: "Ada", age: 36 };
localStorage.setItem("user", JSON.stringify(user));All lessons in this course
- Storing and Reading Data
- localStorage vs sessionStorage
- Storing Objects with JSON
- Storage Events and Limits