首页 > javascript 的 JSON.parse 出现问题

javascript 的 JSON.parse 出现问题

是这样的,我想尝试使用一个hacker news 的 api,然后

var http = require('http');

var hnApi = 'http://node-hnapi.herokuapp.com/news';

var req = http.get(hnApi, function(res) {
  res.on('data', function(chunk) {
    console.log(chunk.toString());
  });
});

这样是没有问题的,真的在终端输出结果了,但是,我想用 JSON.parse 把那个字符串转成对象,就出问题了

var http = require('http');
var hnApi = 'http://node-hnapi.herokuapp.com/news';
var news;

var req = http.get(hnApi, function(res) {
  res.on('data', function(chunk) {
    console.log(chunk.toString());
    news = JSON.parse(chunk.toString());
  });
});

它提示:

undefined:1
n":"codepicnic.com"},{"id":9747414,"title":"A Sea Change in Treating Heart Att
SyntaxError: Unexpected end of input

后来我查了一下,找到了类似这样的答案: http://stackoverflow.com/questions/30942462/json-with-line-breaks-can-...

大概是换行符的问题,然后我再次尝试:

var http = require('http');
var hnApi = 'http://node-hnapi.herokuapp.com/news';
var news;

var req = http.get(hnApi, function(res) {
  res.on('data', function(chunk) {
    console.log(chunk.toString());
    news = JSON.parse(chunk.toString().replace(/\n/g, ''));
  });
});

但是还是同样的跟上面的那段代码一样报错,这是为什么呢?


你的数据没有接收完你就执行了解析动作,结果 肯定 是错的,建议你找一个获取数据例子看一下。
应该是有个end事件的,在data事件中将接收到的数据组合起来,在end事件中进行解析。

手机码字,不太方便例子从就自己找吧。

例子

http://davidwalsh.name/nodejs-http-request

例子中的代码

var http = require('http');

function getTestPersonaLoginCredentials(callback) {

    return http.get({
        host: 'personatestuser.org',
        path: '/email'
    }, function(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {

            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            callback({
                email: parsed.email,
                password: parsed.pass
            });
        });
    });

}

【热门文章】
【热门文章】