9

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?

Andy
  • 61,948
  • 13
  • 68
  • 95
mickdeez
  • 507
  • 3
  • 7
  • 16
  • I also noticed on JSONViewer that when I use the url to retrieve comments, it pulls [0] and [1], 0 having the original data for the post, and 1 having the data for the comments. Maybe I need to specify to look at [1]? – mickdeez Feb 05 '14 at 14:31

1 Answers1

9

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)
  });
});
  • I take that back... it works sometimes. Not other times though. It's weird. Here's my fiddle if you fancy having a look - http://jsfiddle.net/elliotmersch/bpZXL/ – mickdeez Feb 05 '14 at 14:46
  • Nope, it is working. Except posting at the bottom of the div instead of after each post. I think I just need a new div from here. – mickdeez Feb 05 '14 at 14:54