javascriptjsonhacker-news-api

Unable to call JSON data from Hacker News API


I'm trying to use Hacker News API , i am able to call the API and make the request to fetch the stories. As per their API documentation the source URL must contain the ID(required) to access the stories' content, I am getting the correct URL in the console and clicking on the URL gives the appropriate JSON but beyond that I am unable to use/call the JSON content like author name,title etc.

JS CODE:

var records;
var userRecords;
var fileJson;
var startRequest = new XMLHttpRequest();
var sourceUrl = "https://hacker-news.firebaseio.com/v0/";
var sourceUrlAdd = "showstories.json";
var finalURL = sourceUrl + sourceUrlAdd;

startRequest.open("GET",finalURL);
startRequest.onload = function() {
    fileJson = JSON.parse(startRequest.responseText);
    for(var i = 0 ; i < fileJson.length; i++) {
        userRecords = sourceUrl + fileJson[i] + ".json";
    }
}
startRequest.send();

How do I make it work??


Solution

  • Looking at the information on: GitHub

    Your URL in the loop should be modified to:

        for(var i = 0 ; i < fileJson.length; i++) {
           userRecords = sourceUrl + "/item/" + fileJson[i] + ".json";
        }
    

    Your code doesn't look complete as the loop will just overwrite userRecords for every iteration, if you want to store them:

        userRecords = [];
        for(var i = 0 ; i < fileJson.length; i++) {
           userRecords.push(sourceUrl + "/item/" + fileJson[i] + ".json");
        }
    

    The above will give you an array populated with all the results.

    For example this is the content from the first item in the userRecords array:

        {"by":"ntrippar"
        ,"descendants":45
        ,"id":15853345
        ,"kids"[15858055,15854752,15856479,15854664,15858253,15856298,15854305,15855332,15858118,15857061,15854116]
        ,"score":159
        ,"time":1512494533
        ,"title":"Show HN: SeKey: An SSH Agent for OS X, Using Secure Enclave and TouchID, in Rust"
        ,"type":"story"
        ,"url":"https://github.com/ntrippar/sekey"}
    

    If you parse the above it will translate into an object.