node.js - javascript 的 JSON.parse 出现问题
PHP中文网
PHP中文网 2017-04-10 15:25:01
0
0
251

是这样的,我想尝试使用一个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, ''));
  });
});

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

PHP中文网
PHP中文网

认证高级PHP讲师

全員に返信(0)
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!