【发布时间】:2015-08-16 02:59:21
【问题描述】:
我正在尝试解析来自我正在使用的 API 的 JSON 响应。我没有直接访问该文件的权限,我可以对响应进行字符串化,但我根本无法解析 JSON,理想情况下,我希望变量中的“display_name”值。
这是我所拥有的:
var api = require('twitch-irc-api');
api.call({
channel: null,
method: 'GET',
path: '/channels/greatbritishbg/follows',
options: {
limit: 1,
offset: 0
}
}, function(err, statusCode, response) {
if (err) {
console.log(err);
return;
}
console.log('Status code: ' + statusCode);
console.log('Response from Twitch API:');
console.log(JSON.stringify(response));
console.log(JSON.parse(response);
});
字符串化响应:
来自 Twitch API 的响应: {"关注":[{"created_at":"2015-06-02T06:11:10Z","_links":{"self":"https://api.t witch.tv/kraken/users/feddecampo/follows/channels/greatbritishbg"},"通知 s":false,"user":{"_id":50947595,"name":"feddecampo","created_at":"2013-11-01T17: 22:49Z","updated_at":"2015-05-30T19:50:21Z","_links":{"self":"https://api.twitch .tv/kraken/users/feddecampo"},"display_name":"FeddeCampo","logo":"http://static- cdn.jtvnw.net/jtv_user_pictures/feddecampo-profile_image-d4f7de23b28e0a86-300x30 0.jpeg","bio":"Playstation MVP Sony and PS fan","type":"user"}}],"_total":2315, "_links":{"self":"https://api.twitch.tv/kraken/channels/greatbritishbg/follows?d irection=DESC&limit=1&offset=0","next":"https://api.twitch.tv/kraken/channels/gr eatbritishbg/follows?direction=DESC&limit=1&offset=1"}}
【问题讨论】:
-
试试
console.log(response.follows[0].user.display_name); -
"...但我根本无法解析 JSON" - 使用
JSON.parse时会发生什么?您能否至少提供一个返回数据结构的示例,以防止人们不得不查看 API 文档... -
@thefourtheye 你太棒了。谢谢。