function fetchAPI(string) {
return fetch(string).then(function(response) {
return response.json();
}).then(function(json) {
return json;
});
}
try {
fetchAPI(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).then(
function(result1) {
delete result1.success;
delete result1.page;
delete result1.totalAuctions;
delete result1.lastUpdated;
var pages = result1.totalPages;
delete result1.totalPages;
// eslint-disable-next-line no-shadow
for (var page = 0; page < pages; page++) {
fetchAPI(`https://api.hypixel.net/skyblock/auctions?key=${apikey}&page=${page}`).then(function(results) {
delete results.success;
delete results.page;
delete results.totalAuctions;
delete results.lastUpdated;
delete results.totalPages;
var i = 0;
for (i = 0; i < results.auctions.length; i++) {
// eslint-disable-next-line quotes
if (results.auctions[i].item_name != "Enchanted Book") {
delete results.auctions[i];
}
}
fs.appendFile('finalresult.json', JSON.stringify(results), err => {
if (err) console.log(err);
});
});
}
},
});
}
catch (error) {
console.log(error);
}
在代码中,我从返回 JSON 响应的 API(fetchAPI 函数)获取信息。要从 API 获取所有信息,我需要查询特定端点的每个页面,因此循环for (var page = 0; page < pages; page++)。然后,我需要过滤 JSON:
for (i = 0; i < results.auctions.length; i++) {
// eslint-disable-next-line quotes
if (results.auctions[i].item_name != "Enchanted Book") {
delete results.auctions[i];
}
}
最后,我需要将每一页的所有 JSON 信息都保存到一个文件中。唯一的问题是,将来我需要从该文件中读取,而当我读取时fs.appendFile('finalresult.json', JSON.stringify(results));,它不会保留 JSON 格式。有没有一种方法可以基本上制作一个由 API 数据组成的长 JSON 文件?
小唯快跑啊
相关分类