Search code examples
javascriptjqueryjsonapireddit

Reddit API - difference between API and appending .json and getting front page info


I am newcomer with making applications dealing with other API's, especially ones that require OAuth authentication.

For now, I am trying to simply fetch information about the front page listing of Reddit in my application.

I am looking at this Reddit API doc here, but then I am reading that to get a JSON representation of Reddit you just have to add a .json after the url.

So I am sending a HTTP GET request like:

$(document).ready(function () {

    httpGetAsync("https://www.reddit.com/.json");

});

function httpGetAsync(url) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            alert(JSON.stringify(xmlHttp.responseText, null, 4));
    }
    xmlHttp.open("GET", url, true); // true for asynchronous 
    xmlHttp.send(null);
}

But this seems to be only returning what seems is the LAST post on the reddit page or maybe I cannot tell since the alert box cannot show the enormous JSON response?

I figured this was the case and tried:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        parseResponse(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous 
xmlHttp.send(null);


function parseResponse(responseText) {
var x = (JSON.parse(responseText));
alert(x.count);

}

but got a undefined in the alert box. Any ideas?

Goal is to get the 25 front page of reddit JSON responses information (identifiers)


Solution

  • You might want to use jQuery to retrieve and parse the data:

    $.getJSON( "https://www.reddit.com/.json", function( data ) {
      $.each( data.data.children, function( i, obj ) {
         console.log(obj.data.id);
      });
    });
    

    I made a working example for you that retrieves the first 25 IDs:

    https://jsfiddle.net/enmpw8qf/