I want to loop true certain elements, in this case all with the class “widget”, and get there id and title(later on more stuff), store it as JSON in the localStorage(must be a string so we stringify the data), get the data from the localStorage and loop the results. All goes well until i want to loop it(JSON output is valid), this wont work, and i have been working on it for more than a day now so i hope that anybody see what i am doing wrong.
(yes i have looked on the web)
I am still a noob at this so if there are better ways to store and loop this let me know.
// html
<div class="widget" id="w1">
<h2>some text</h2>
</div>
...
...
...
// setting the data
var storeStr = '';
storeStr += '{"widget":[';
$('.widget').each(function(){
storeStr += '{';
storeStr += '"id": "'+$(this).attr('id')+'",';
storeStr += '"title": "'+$(this).children('h2').text()+'"';
storeStr += '},';
});
storeStr += ']}';
var storeStr = storeStr.replace(/\},]/g,'}]');// comma cleanup
localStorage.setItem('thelskey', storeStr);
// output(json valid)
{
"widget":[
{"id": "w1","title": "xxxxx"},
{"id": "w2","title": "xxxxx"},
{"id": "w3","title": "xxxxx"},
{"id": "w4","title": "xxxxx"}
]
}
// the loop
var json = JSON.parse(localStorage.getItem('thelskey'));
for(var key in json){
//output
}
Your JSON object only has a single key,
"widget". So there’s no point in looping through it. If you want to get all of the widget data, you need to loop through each item under thewidgetproperty, i.e.Otherwise, don’t wrap the array in the extra object, and just construct your JSON as:
I get the feeling you’re not understanding the structure of your JSON object, which is currently:
You can sort of think of it as a 3-dimensional associative array (or 3 layers of associative arrays nested within one another):
You’re currently trying to loop through the first dimension of
$json, which only has a single item. So the error you’re getting is because you’re trying to access:when in fact you should be trying to access:
Or you can simply remove the first layer of your data structure and just access:
To avoid such problems in the future, make use of a JS console like Firebug’s or node.js’ or the built-in JS consoles that most modern browsers now have. Simply doing something like:
or
would have revealed the problem.