Photo by Suzanne D. Williams on Unsplash
How Serialization and Deserialization in JS helps in storing Structured data in local Storage or session Storage
This blog will help you understand how Java Script helps in storing Structured Data in Local storage and session storage using Examples.
Both local Storage and session Storage in JavaScript only support storing strings. However, in real-world applications, we often need to store structured data like objects, arrays, and nested structures. Serialization and deserialization enable us to store and retrieve such data efficiently.
Why Serialization is Needed for local Storage and session Storage?
Since localStorage.setItem(key, value)
and sessionStorage.setItem(key, value)
only accept string values, we need to serialize JavaScript objects or arrays before storing them.
Serialization: Converts a JavaScript object into a string format (
JSON.stringify()
) so it can be stored.Deserialization: Converts the stored string back into an object (
JSON.parse()
) when retrieved.
Example: Storing and Retrieving a Complex Object in localStorage
Let's say we have a user settings object that we want to store and retrieve.
Storing the object (Serialization)
const userSettings = {
theme: "dark",
language: "English",
notifications: { email: true, sms: false },
};
// Convert the object to a string before storing
localStorage.setItem("userSettings", JSON.stringify(userSettings));
console.log("Data stored in localStorage:", localStorage.getItem("userSettings"));
Things to note
JSON.stringify(userSettings)
converts the JavaScript object into a JSON string.The serialized string is stored in
localStorage
.
Retrieving the object (Deserialization)
const storedSettings = localStorage.getItem("userSettings");
// Convert the string back into an object
const parsedSettings = storedSettings ? JSON.parse(storedSettings) : {};
console.log("Retrieved settings:", parsedSettings);
console.log("Theme:", parsedSettings.theme); // Output: "dark"
What happens here?
localStorage.getItem("userSettings")
retrieves the serialized JSON string.JSON.parse(storedSettings)
converts it back into a JavaScript object.
How This Helps in Real Applications?
Persistent User Preferences
Storing settings like theme, language, notification preferences, etc.
function savePreferences(preferences) {
localStorage.setItem("preferences", JSON.stringify(preferences));
}
function loadPreferences() {
const savedPreferences = localStorage.getItem("preferences");
return savedPreferences ? JSON.parse(savedPreferences) : { theme: "light", language: "English" };
}
Now, even if the user refreshes or reopens the app, their preferences persist.
Session-Based Authentication Data (sessionStorage
)
For temporary session storage, we can use sessionStorage
instead of localStorage
. The data will be cleared when the tab is closed.
const sessionUser = { id: 123, username: "ram-bhardwaj" };
// Store session data
sessionStorage.setItem("sessionUser", JSON.stringify(sessionUser));
// Retrieve session data
const loggedInUser = JSON.parse(sessionStorage.getItem("sessionUser"));
console.log(loggedInUser.username); // Output: "ram-bhardwaj"
If you have any questions please feel free to add in comments, I’ll surely answer it.