JavaScript – Save Objects in HTML5 Session Storage

This post shows you how to save/store a JavaScript object in HTML5 Session Storage. To do this, we need to convert the object to a JSON string by using JSON.stringify method.

 

Here is the code example:

/// 1. Saving data to sessionStorage

// user object
var user = {
    name: 'Alex',
    age: 25,
    gender: 'male'
};

// convert the object to JSON string
var userJsonString = JSON.stringify(user);

// save it to sessionStorage
sessionStorage.setItem('user', userJsonString);


/// 2. Reading data from sessionStorage

// get saved data from sessionStorage
var savedUserJsonString = sessionStorage['user'];

// convert it to JavaScript object
var savedUserObject = JSON.parse(savedUserJsonString);

In the above code, we use JSON.stringify method to convert the object to JSON string before saving it to sessionStorage. And then use JSON.parse method to convert the saved data back to JavaScript object when getting data from sessionStorage.

 

Learn more about How to Store Data in HTML5 Session Storage.

Leave a Reply

avatar