javascript - Cant get the JSON output to loop -
i want loop true elements, in case class "widget", , there id , title(later on more stuff), store json in localstorage(must string stringify data), data localstorage , loop results. goes until want loop it(json output valid), wont work, , have been working on more day hope see doing wrong.
(yes have looked on web)
i still noob @ if there better ways store , loop let me know.
// html
<div class="widget" id="w1"> <h2>some text</h2> </div> ... ... ...
// setting 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"} ] }
// loop
var json = json.parse(localstorage.getitem('thelskey')); for(var key in json){ //output }
your json object has single key, "widget"
. there's no point in looping through it. if want of widget data, need loop through each item under widget
property, i.e.
for (var key in json.widget) { // output }
otherwise, don't wrap array in object, , construct json as:
[ {"id": "w1","title": "xxxxx"}, {"id": "w2","title": "xxxxx"}, {"id": "w3","title": "xxxxx"}, {"id": "w4","title": "xxxxx"} ]
i feeling you're not understanding structure of json object, currently:
{ widget: [ { id: "w1", title: "xxxxx" }, { id: "w2", title: "xxxxx" }, { id: "w3", title: "xxxxx" }, ... ] }
you can sort of think of 3-dimensional associative array (or 3 layers of associative arrays nested within 1 another):
/* in php code because js doesn't have associative arrays */ $json = array( // first layer 'widget' => array( // second layer 0 => array( // third layer 'id' => 'w1', 'tit;e' => 'xxxxx' ), 1 => array( // third layer 'id' => 'w2', 'tit;e' => 'xxxxx' ), 2 => array( // third layer 'id' => 'w3', 'tit;e' => 'xxxxx' ), ... ) );
you're trying loop through first dimension of $json
, has single item. error you're getting because you're trying access:
$json[$key]['widget']['id'] // $key = 'widget'
when in fact should trying access:
$json['widget'][$key]['id'] // $key = 1, 2, 3, 4
or can remove first layer of data structure , access:
$json[$key]['id'] // $key = 1, 2, 3, 4
to avoid such problems in future, make use of js console firebug's or node.js' or built-in js consoles modern browsers have. doing like:
console.log(json);
or
foreach (key in json) { console.log(key); console.log(json[key]); }
would have revealed problem.
Comments
Post a Comment