读取API(JSON)的内容

这是我要求的帮助,我目前正在讨论chatbot作为我的第一个js项目,到目前为止进展顺利。 我希望我的机器人能够获得特定的信息,例如玩家,然后将其发回给用户。

以下是我请求数据的API的链接: https : //minecraft-statistic.net/en/server/198.27.89.248_25629/json

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

为你提供一些有用的方法: 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(); 

要进行快速testing,请转到Firefox,按Shift+F4 ,粘贴并运行此操作并检查控制台。

将您的属性从JSON加载到对象中

所以想象这是你的API的JSON

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

然后得到'currentPlayers'的值你可以使用这个语法

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