javascripthtmlsessionstorage

Unable to get the value from a JavaScript object


I have created a JSON object and put it under session object.

How can I retrieve the value from the JSON?

This is my program

var datainsession = {"firstName":"John", "lastName":"Doe"};

var keyname = 'test';

window.sessionStorage.setItem(keyname + '', datainsession);

var val_sess = window.sessionStorage.getItem(keyname);

var firstname = val_sess.firstName;

alert(firstname);

http://jsfiddle.net/5bea0mr2/3/

Could you please tell me how I can retrieve the first name?


Solution

  • JSON is represented by a string, not an object. It's simply a JavaScript object with string keys. You'll need to use JSON.stringify() and JSON.parse() to convert the JavaScript object.

    Try the following:

    var datainsession = {
      firstName: "John",
      lastName: "Doe"
    };
    
    var keyname = 'test';
    
    window.sessionStorage.setItem(keyname, JSON.stringify(datainsession));
    
    var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
    
    var firstname = val_sess.firstName;
    
    alert(firstname);