Home > Enterprise >  How to write array data to json?
How to write array data to json?

Time:02-24

How to write the data that the loop passes to the array "eventsPolygon", to json. This array returns 4 args. With this method, I get the error "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined"

async function main() {
  console.log("Start checking rewards")
  const currentBlockNumberPolygon = await maticProvider.getBlockNumber() - 1
  const currentBlockNumberBsc = await bscProvider.getBlockNumber() - 1

  const oldestBlockNumberPolygon = 22939848
  const oldestBlockNumberBsc = 13763979


  const eventFilterPolygon = Missions.filters.RewardToPay()
  const eventFilterBsc = Rewards.filters.RewardPayed()

  let eventsPolygon = []
  let eventsBsc = []

  for (let i = oldestBlockNumberPolygon; i < currentBlockNumberPolygon - 10000; i  = 10000) {
    const eventsLoop = await Missions.queryFilter(eventFilterPolygon, i, i   10000)
    eventsPolygon = eventsPolygon.concat(eventsLoop)

    const jsonData = JSON.stringify(eventsPolygon);
    fs.writeFile('eventsBsc.json', jsonData.finished)

    console.log(i)
  }

  //for(let i = oldestBlockNumberBsc; i < currentBlockNumberBsc-10000; i =10000) {
  //const eventsLoop = await Rewards.queryFilter(eventFilterBsc, i, i 10000)
  // eventsBsc = eventsBsc.concat(eventsLoop)
  //console.log(i)
  //}

  console.log('a')
}

CodePudding user response:

JSON.stringify returns a string representation of your JSON. So you cannot do this:

fs.writeFile('eventsBsc.json', jsonData.finished)

Simply write jsonData to the file:

await fs.writeFile('eventsBsc.json', jsonData);

Be aware that this function is async. You need to await it

  • Related