Storing JSON Objects in HTML5 Local Storage
In one my recent application (HTML 5 static mobile app) I have a requirement to persist couple of JSON objects across the application. Earlier, this was done with cookies.
With HTML5, web pages can store data locally within the user’s browser using Web Storage. Web Storage is more secure and faster compare to cookies. The data is not included with every server request, but used only when asked for. It is also possible to store large amounts of data, without affecting the website’s performance. Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari.
Web storage provides two new objects for storing data on the client:
-
localStorage – stores data with no expiration date
-
sessionStorage – stores data for one session
I decide to use local Storage option, Here is the code snippet:
How to store the object in local storage?
if (typeof (Storage) !== "undefined") { var person = { "firstName": "Shravan Kumar", "lastName": "Kasagoni", "age": "25", "mobileNumber": "1234567890" }; localStorage.setItem('person', person); } else { alert("Sorry, your browser does not support web storage..."); }
-
First check whether your browser supports Web Storage or not.
-
If yes, use setItem() method of localStorage object to store our object.
How to retrieve the object from local storage?
if (typeof (Storage) !== "undefined") { var person = localStorage.getItem('person'); alert(typeof (person)); } else { alert("Sorry, your browser does not support web storage..."); }
-
We can use getItem() method of localStorage object to retrieve our object.
-
When we do a type check, it says retrieved object type is string, but we stored a JSON object.
In Web Storage data is stored as string key/value pairs. We can’t directly store/retrieve objects from local storage. Work around for this, simply use JSON.parse(obj) method to convert the retrieved object to JSON object.
var person = localStorage.getItem('person'); var persons = JSON.parse(person);
Simple & well know technique, thought of sharing.
nice article! but when i am using JSON.Parse(person). it throws an error saying invalid character. I could not figure out what was that. here is my code.
$(document).ready(function () {
if (typeof (Storage) != “undefined”) {
var emp = {Name: “Chris”, Age: 30, IsPermanent: true };
localStorage.setItem(“employee”, emp);
}
else { alert(“sorry your browser does not support web storage.”); }
$(“#btnGetEmp”).click(function () {
if (typeof (Storage) != “undefined”) {
var emp = localStorage.getItem(“employee”);
//alert(typeof (emp)); // string
var emps = JSON.parse(emp); // throws an error 0x800a03f6 – JavaScript runtime error: Invalid character
}
else { alert(“sorry your browser does not support web storage.”); }
});
});
can you try JSON.parse(emp.employee);
use
emp = JSON.stringify(emp); before storing in local storage