Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract url data from Reddit API using JSON

I'm trying to extract the image post URLs from a subreddit feed, and render <img> elements on my page.

Been trying to hack together the .getJSON() Flickr example from the jQuery Docs for a while now and I'm not getting anywhere.

Code in question:

$.getJSON('http://www.reddit.com/r/pics.json', function (data) {
  $.each(data.children, function (i, item) {
    $('<img/>').attr("src", url).appendTo("#images");
  });
});

In the body, I have the element: div#images

I understand that I need to use JSONP, but not sure how. Can somebody point me in the right direction?

like image 877
izolate Avatar asked Nov 19 '11 01:11

izolate


People also ask

Is there an API for Reddit?

The Reddit API (Application Programming Interface) allows you to extract data, or post to Reddit using a web application or your preferred programming language.

Does Reddit have a free API?

All of the Reddit APIs listed are free to use, although the Socialgrep API — used for searching posts and comments dating back to 2010 — does come with features that are locked behind a pay wall.

Can you get data from Reddit?

Some of your information is available via the Reddit mobile app, however, it's easiest to find what you're looking for by visiting reddit.com on your computer's web browser and logging in to your account. To request a copy of your Reddit data and information, fill out a data request form.


1 Answers

You are using the wrong url. Use this:

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) { 
    // Do whatever you want with it.. 
});

EDIT : Working example based on your fiddle in the comments.

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) { 
    $.each(data.data.children, function(i,item){
        $("<img/>").attr("src", item.data.url).appendTo("#images");
    });
});

You should use data.data.children and not data.children

like image 141
pradeek Avatar answered Oct 05 '22 22:10

pradeek