Reputation: 32321
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?
Upvotes: 2
Views: 1196
Reputation: 7057
You need to convert it to a string on setting, and parse it when you get it out. This method only stores a string, but JSON methods can get around that. Eg.
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
var val_sess = window.sessionStorage.getItem('test');
var obj = JSON.parse(val_sess).firstName;
alert(obj);
Upvotes: 2
Reputation: 12508
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);
Upvotes: 4
Reputation: 22817
window.sessionStorage.setItem
can only store serialised objects.
So you have to serialise it first via JSON.stringify
:
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession))
Then to retrieve it via JSON.parse
:
var val_sess = window.sessionStorage.getItem(keyname);
var obj = JSON.parse(val_sess);
// obj.firstName is what you need.
Upvotes: 5
Reputation: 128791
Session storage can only hold strings, not objects. Your session here ends up holding your object converted to a string ("[Object object]"
), and not the object itself.
To get around this we can firstly convert the object to a JSON string using JSON.stringify()
:
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
-> '{"firstName":"John","lastName":"Doe"}'
Then when pulling it convert it back to an object by using JSON.parse()
:
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
-> {"firstName":"John","lastName":"Doe"}
Upvotes: 12