UnKnown UnKnown - 9 months ago 37
Javascript Question

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;



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

Answer Source

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;