2017-02-26 128 views
2

以下是我正在请求帮助的内容,目前我正在讨论chatbot作为我的第一个js项目,目前进展顺利。我希望我的机器人能够获得特定的信息,例如玩家,然后将其发回给用户。阅读API的内容(JSON)

这里的链接我从请求数据的API:https://minecraft-statistic.net/en/server/198.27.89.248_25629/json

我如何去从API获取一个数据? 所有帮助表示赞赏。

+2

请给更多的信息 –

+2

你忘了问你的问题 –

回答

0
的“currentPlayers的价值

一些有用的方法给你: XMLHttpRequest(),JSON.parse()JSON.stringify()

使用并更改以下代码以获得您需要的回应。

var xhr = new XMLHttpRequest(); 
xhr.open("get", "https://minecraft-statistic.net/en/server/198.27.89.248_25629/json"); 
xhr.setRequestHeader("accept", "application/json"); 
xhr.onload = function() { 
    var response = JSON.parse(xhr.responseText); 
    // list all objects 
    for (var key in response) { 
    console.log(key, response[key]); 
    } 
    // list players 
    console.log('players: ' + JSON.stringify(response['counter']['players'])); 
} 
xhr.send(); 

对于一个快速测试去到Firefox,按Shift+F4,粘贴并运行此检查控制台。

0

你的财产装入一个对象从JSON

所以想象这是你的API的JSON

var json = {maxOnline: 8, currentPlayers: ["john", "steve", "bob"]} 

来,然后让你可以使用这个语法

var players = json["currentPlayers"] 
console.log(players[0]); // outputs "john"