views:

59

answers:

1

I'm trying to parse the json grabbed from here. Basically what I do is iterate over the items, sort them, then display them. But I get an error saying data.data.children[i] is undefined.

I can't think why it's doing it though?

var json = 'http://www.reddit.com/reddits/mine/.json';

GM_xmlhttpRequest({
    method: "GET",
    url:    json,
    onload: reddits
});

function reddits(response){
    var txt = response.responseText;
    var data;
    var suggested = document.getElementById('suggested-reddits');
    if(window.JSON && JSON.parse){
        data = JSON.parse(txt);
    }
    else{
        data = eval("("+txt+")");
    }

    suggested.innerHTML += '<span>reddits you\'re subscribed to </span> <ul id="rsub"></ul>';
    GM_addStyle('#rsub{width: 500px;}');
    var reddits = new Array();  
    var rsub = document.getElementById('rsub');

    for(i = 0; i <= data.data.children.length; i++){
        var r = data.data.children[i].data.display_name;
        reddits.push(r);
    }
    sort(reddits);
    for(i = 0; i <= reddits.length; i++){       
        rsub.innerHTML += '<li><a href="#" onclick="set_sr_name(this); return false">' + reddits[i] + '</a></li>';
    }
}
+2  A: 
for(i = 0; i <= data.data.children.length; i++){
    var r = data.data.children[i].data.display_name;
    reddits.push(r);
}

Clear problem is in the for statement. Change the i <= data.data.children.length to i < data.data.children.length. Note the inequality change.

Since arrays in Javascript are 0-indexed, the element at i = data.data.children.length does not exist.

You should probably do the same things for the reddits.length loop.

phsource