为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕姐4208626 2023-03-24 14:13:53
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 文件?
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

对不起。我今天很累,忘记了代码的异步特性。


这是完全有效的示例(即使没有 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) {

  const el = document.getElementById('loader');

  if (count) el.innerText = '' + count + ' of ' + total;

  else el.innerText = 'ALL';

}


function fetchAPI(string) {

  return fetch(string)

   .then(response => response.json());

}


function getAuctionsFromPage(page, totalPages) {

  return fetchAPI(originalUrl + `&page=${page}`)

    .then(result => {

      loaded++;

      showLoaded(loaded, totalPages);

      return result.auctions

    })

    .then(auctions => auctions.filter(auction => auction.item_name == nameToSearch));

}


let loaded = 0;


function collectData(totalPages) {

  const allPages = [];

  loaded = 0;

  for (let i = 0; i < totalPages; i++) {

    allPages.push(getAuctionsFromPage(i, totalPages));

  }

  return Promise.all(allPages)

    .then(auctions => auctions.flat(1))

    .then(auctions => {

      showLoaded();

      return {

        auctions

      }

    });

}


function saveToFile(data) {

  // Put data to file

  fs.appendFile('finalresult.json', JSON.stringify(data), err => {

    if (err) console.log(err);

  });

}


function saveToConsole(data) {

  const jsonData = JSON.stringify(data);

  //console.log(jsonData);

  document.getElementById('console').innerHTML = 'We found ' + data.auctions.length + ' items named ' + nameToSearch + '<br/>Data size is ' + jsonData.length + ' bytes';

}


try {

  document.getElementById('loader').innerText = 'Getting total pages...';

  fetchAPI(originalUrl)

    .then(result => result.totalPages)

    .then(totalPages => collectData(totalPages))

    .then(data => saveToConsole(data));

} catch (error) {

  console.log(error);

}

<div>Loaded: <span id="loader">0</span></div>

<div id="console"></div>

注意:要将数据保存到文件中,您需要更改.then(data => saveToConsole(data)).then(data => saveToFile(data))



查看完整回答
反对 回复 2023-03-24
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信