【发布时间】:2014-06-22 20:16:45
【问题描述】:
我正在尝试使用 Node 中的以下内容解析来自 Songkick API 的响应:
router.post('/', function(req, res) {
var artist = req.body.artist;
var id;
res.render('artist', { title: 'Artist', artist: artist });
http.request({host: 'api.songkick.com', path: '/api/3.0/search/artists.json?query=' + artist + '&apikey=myAPIKey'}, function(res) {
res.on("data", function(chunk) {
id = JSON.parse(chunk).resultsPage.results.artist[0].id;
console.log(id);
http.request({host: 'api.songkick.com', path: '/api/3.0/artists/' + id + '/gigography.json?apikey=Z2JWQTvgk4tsCdDn'}, function(res) {
res.on("data", function(chunk) {
console.log(JSON.parse(chunk).resultsPage.results);
});
}).end();
});
}).end();
});
但是,JSON.parse 失败并显示 SyntaxError: Unexpected token t(最后一个字符会根据请求的艺术家而变化)。
Here's an example API response.
如何修复语法错误?
【问题讨论】:
-
JSON.parse(chunk)
-
你是对的......如果我记录块,它会给我一系列缓冲区。我怎样才能从那些转向可解析的 JSON?
-
我稍微更改了您的代码并发布了答案。虽然它没有经过实际测试。