Retrieving comments from Reddit's API

mickdeez picture mickdeez · Feb 5, 2014 · Viewed 7.2k times · Source

So I've written some code that searches reddits api based on a query and I want it to display comments as well. I have the following code nested inside my $.getJSON statement that pulls each title/post based on your search query, and now I want to display the comment tree for each result thats found (hence why I have it nested in my original getJSON statement)

$.getJSON("http://www.reddit.com/r/" + sub + "/comments/" + id + ".json?", function (data){
  $.each(data.data.children, function (i, item) {
    var comment = item.data.body
    var author = item.data.author
    var postcomment = '<p>[Author]' + author + '<br>' + comment + '</p>'
    results.append(postcomment)
  });
});

I have a feeling I may be structuring the $.each statement wrong or something. I'm just following what I did for the other getJSON statement. Any ideas?

Answer

florianmientjes picture florianmientjes · Feb 5, 2014

The reddit json contains two objects: the post, and the comments. The comments are located at data[1] This should work:

$.getJSON("http://www.reddit.com/r/" + sub + "/comments/" + id + ".json?", function (data){
  $.each(data[1].data.children, function (i, item) {
    var comment = item.data.body
    var author = item.data.author
    var postcomment = '<p>[Author]' + author + '<br>' + comment + '</p>'
    results.append(postcomment)
  });
});