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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With