Search code examples
javascriptjqueryjsonlocal-storagestringify

jQ: Parse localstorage & stringify values


I am storing some values in localStorage using stringify and I'm trying to parse them but it doesn't work for me.

This is how I add the values:

localStorage.setItem('a', JSON.stringify({ userid : '4361', value : '23' }));

And this is how I parse them:

$('p').text(JSON.parse(localStorage.getItem('a')));

Here is the fiddle: http://jsfiddle.net/hrHfG/

Also, I'd like to know how can I parse each value separately. For example, only the userid of 'a', or only the value, if its possible.

Thanks a lot


Solution

  • That is because JSON.parse(localStorage.getItem('a')) returns an object. You cannot use an object like that as an argument in .text().

    This works though:

    $('p').text(JSON.parse(localStorage.getItem('a')).value);