Retrieving comments from Reddit's API
Asked Answered
A

1

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?

Aundreaaunson answered 5/2, 2014 at 14:25 Comment(1)
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]?Aundreaaunson
S
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)
  });
});
Salade answered 5/2, 2014 at 14:38 Comment(2)
I take that back... it works sometimes. Not other times though. It's weird. Here's my fiddle if you fancy having a look - jsfiddle.net/elliotmersch/bpZXLAundreaaunson
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.Aundreaaunson

© 2022 - 2024 — McMap. All rights reserved.