简体   繁体   中英

Unexpected End of JSON Input when pulling JSON from Reddit

I am trying to pull some reddit posts from their json feed, as it is done in this example :

var http = require('http');


function getRedditPosts() {
  var url = "http://www.reddit.com/r/jokes/new/.json?limit=1";

  var request = http.get(url, function(response) {
    var json = '';
    response.on('data', function(chunk) {
      json += chunk;
    });

    response.on('end', function() {
      var redditResponse = JSON.parse(json);
      redditResponse.data.children.forEach(function(child) {
    if(child.data.domain !== 'self.node') {
      console.log('-------------------------------');
      console.log('Author : ' + child.data.author);
      console.log('Domain : ' + child.data.domain);
      console.log('Title : ' + child.data.title);
      console.log('URL : ' + child.data.url);
    }
      });
    })
  });
  request.on('error', function(err) {
    console.log(err);
  });
}

getRedditPosts();

The problem is that I am getting a unexpected end of JSON input. Why is that?

undefined:1

SyntaxError: Unexpected end of JSON input at Object.parse (native) at IncomingMessage. (/Users/felix/Desktop/Dev/npmTest/index.js:14:33) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9)

So, there is a typo in your url reddit.com/r/jokes/new.json?limit=1 .

And you should use https instead of http package because reddit is https. Corrected code :

var http = require('https');


function getRedditPosts() {
  var url = "https://www.reddit.com/r/jokes/new.json?limit=1";

  var request = http.get(url, function(response) {
    var json = '';
    response.on('data', function(chunk) {
      json += chunk;
    });

    response.on('end', function() {
      var redditResponse = JSON.parse(json);
      redditResponse.data.children.forEach(function(child) {
    if(child.data.domain !== 'self.node') {
      console.log('-------------------------------');
      console.log('Author : ' + child.data.author);
      console.log('Domain : ' + child.data.domain);
      console.log('Title : ' + child.data.title);
      console.log('URL : ' + child.data.url);
    }
      });
    })
  });
  request.on('error', function(err) {
    console.log(err);
  });
}

getRedditPosts();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM