how to save the result of a loop in JSON?

I have created a loop in an asynchronous function that gets data from an external page. I would like the result to be saved in JSON. However, my script doesn’t work as expected.

for (let tokenId = 0; tokenId < 5; tokenId++) {
        let result = await Gateway.tokenURI(tokenId);
        fs.writeFileSync("ogUris.json", result)


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are calling fs.writeFileSync() inside your loop where each call to that function will replace/overwrite the previous results.

If you want to save an array of results in your JSON, then you can accumulate the results into an array and then write the array at the end.

const results = [];
for (let tokenId = 0; tokenId < 5; tokenId++) {
    try {
        let result = await Gateway.tokenURI(tokenId);
    } catch(e) {
 fs.writeFileSync("ogUris.json", JSON.stringify(results));

This will leave you with an array of tokenURIs in JSON format in the file.

Method 2

This is not working because for loop doesn’t wait for await Gateway.tokenURI(tokenId) to provide you any response.You can try using promise.all

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x