personaelit
personaelit

Reputation: 1653

Storing an Array in localStorage Using JSON.stringify

I just learned about jquery's .makeArray and I am trying to use JSON.stringify to store the array in localStorage but I am having unexpected results.

This works:

var links = {'one': 1, 'two': 2 };
var setstr = JSON.stringify(links);

localStorage.setItem('strlinks', setstr);
var getstr = localStorage.getItem('strlinks');
console.log(getstr); //Returns what's expected - '{"one":1, "two":2}'

This doesn't:

var links = $.makeArray($('a'));

alert(links); //Returns list of links
var setstr = JSON.stringify(links);

localStorage.setItem('strlinks', setstr);
var getstr = localStorage.getItem('strlinks');
console.log(getstr); //Returns '[]'

Any ideas about what I'm doing wrong?

Upvotes: 3

Views: 8815

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

links contains circular references, so it can't be serialized to JSON. Chrome 5.0.375.99 gives the error:

TypeError: Converting circular structure to JSON

You have to somehow remove these circular references. Of course, it depends what info you care about. Here's a simplified version:

var flatLinks = $.map(links, function(el)
                             {
                              return {href: el.href, text: el.textContent};
                             }); 
var setstr = JSON.stringify(flatLinks);

Upvotes: 3

bobince
bobince

Reputation: 536389

$('a') selects all the links (HTMLAnchorElements) on the page.

Elements are DOM nodes defined by their identity and presence in the document. They are not simple values that JSON can represent. If you look at what JSON.stringify() returns for them, it's just {}: JSON says all it knows about the object is that it's an Object.

It doesn't make any sense to attempt to put a Node inside a localStorage; what do you expect to get back when you read the storage tomorrow? A Node object that was part of a document the user closed and destroyed yesterday?

If you want to remember where the links pointed to, you should get that from their href properties, as a String—a simple value type that can safely be remembered by localStorage.

Upvotes: 0

Related Questions