当一个不存在时组合 2 个 JSON 对象

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 文件?


慕姐4208626
浏览 94回答 1
1回答

小唯快跑啊

对不起。我今天很累,忘记了代码的异步特性。这是完全有效的示例(即使没有 apiKey)。你可以运行它://const originalUrl = `https://api.hypixel.net/skyblock/auctions?key=${apikey}`;const originalUrl = `https://api.hypixel.net/skyblock/auctions?rnd=1`;const nameToSearch = 'Enchanted Book';function showLoaded(count, total) {&nbsp; const el = document.getElementById('loader');&nbsp; if (count) el.innerText = '' + count + ' of ' + total;&nbsp; else el.innerText = 'ALL';}function fetchAPI(string) {&nbsp; return fetch(string)&nbsp; &nbsp;.then(response => response.json());}function getAuctionsFromPage(page, totalPages) {&nbsp; return fetchAPI(originalUrl + `&page=${page}`)&nbsp; &nbsp; .then(result => {&nbsp; &nbsp; &nbsp; loaded++;&nbsp; &nbsp; &nbsp; showLoaded(loaded, totalPages);&nbsp; &nbsp; &nbsp; return result.auctions&nbsp; &nbsp; })&nbsp; &nbsp; .then(auctions => auctions.filter(auction => auction.item_name == nameToSearch));}let loaded = 0;function collectData(totalPages) {&nbsp; const allPages = [];&nbsp; loaded = 0;&nbsp; for (let i = 0; i < totalPages; i++) {&nbsp; &nbsp; allPages.push(getAuctionsFromPage(i, totalPages));&nbsp; }&nbsp; return Promise.all(allPages)&nbsp; &nbsp; .then(auctions => auctions.flat(1))&nbsp; &nbsp; .then(auctions => {&nbsp; &nbsp; &nbsp; showLoaded();&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; auctions&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}function saveToFile(data) {&nbsp; // Put data to file&nbsp; fs.appendFile('finalresult.json', JSON.stringify(data), err => {&nbsp; &nbsp; if (err) console.log(err);&nbsp; });}function saveToConsole(data) {&nbsp; const jsonData = JSON.stringify(data);&nbsp; //console.log(jsonData);&nbsp; document.getElementById('console').innerHTML = 'We found ' + data.auctions.length + ' items named ' + nameToSearch + '<br/>Data size is ' + jsonData.length + ' bytes';}try {&nbsp; document.getElementById('loader').innerText = 'Getting total pages...';&nbsp; fetchAPI(originalUrl)&nbsp; &nbsp; .then(result => result.totalPages)&nbsp; &nbsp; .then(totalPages => collectData(totalPages))&nbsp; &nbsp; .then(data => saveToConsole(data));} catch (error) {&nbsp; console.log(error);}<div>Loaded: <span id="loader">0</span></div><div id="console"></div>注意:要将数据保存到文件中,您需要更改.then(data => saveToConsole(data))为.then(data => saveToFile(data))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript