HTML and CSS Reference
In-Depth Information
easily get this data back to an object once it has been saved. This is where JSON comes in. Using JSON, you can
convert a JavaScript object to a JSON string and then save that. Then when you want to retrieve your object, you
simply retrieve the JSON and parse it.
Storing Objects
Storing your objects using JSON is fairly simple. The following example shows how to do it. Fire up your console
and give it a go.
// Create an object.
var myObject = {};
myObject.name = “book";
myObject.color = “green";
myObject.pages = 292;
// Convert the object to JSON.
var json = JSON.stringify(myObject);
// Store the JSON using localStorage.
localStorage.setItem(“myObject", json);
In this example, you created a new JavaScript object, converted it to JSON, and then saved it on the client using
LocalStorage.
Retrieving Objects
So that's great: You have your JavaScript object converted to JSON and safely stored in LocalStorage. But what if
you want to retrieve that object? This is where the JSON.parse() function comes in handy.
The example below shows how you can retrieve your object by retrieving the JSON from the datastore and convert-
ing it to a JavaScript object.
// Get the JSON from the datastore.
var retrievedJson = localStorage.getItem(“myObject");
// Convert the JSON to a JavaScript Object.
var myNewObject = JSON.parse(retrievedJson);
Now, if you inspect the myNewObject variable in the console, you should see that your JavaScript object is back!
This is shown in Figure 12-8.
Figure 12-8 Retrieving and parsing an object from LocalStorage.
Search WWH ::




Custom Search