Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving comments from Reddit's API

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?

like image 805
mickdeez Avatar asked Feb 05 '14 14:02

mickdeez


People also ask

How do I see comments on Reddit?

You can get the comments for a post/submission by creating/obtaining a Submission object and looping through the comments attribute. To get a post/submission we can either iterate through the submissions of a subreddit or specify a specific submission using reddit. submission and passing it the submission url or id.

How do you reply to a comment on PRAW?

If you're looking for how to reply to a comment, you want to use the Comment#reply method. If you have the comment bound to variable name c , then you can do the following: c. reply("Here is a reply to your comment.")

Does Reddit allow scraping?

Reddit requires you to be authenticated to scrape the Reddit website with their API. Apify doesn't require you to even have a Reddit account. The use of Reddit's API for commercial use requires special authorization.

Can you get data from Reddit?

To request a copy of your Reddit data and information, fill out a data request form by following these steps: Visit https://www.reddit.com/settings/data-request on your computer's web browser. Log in to the Reddit account you'd like to request data from. Follow the instructions and click Submit.


1 Answers

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)
  });
});
like image 61
florianmientjes Avatar answered Nov 16 '22 16:11

florianmientjes