Reputation: 37
I've written a script to read data from a website using an API and i'd like to write the output in a google sheet. There are 4 data items per ID of a json object and i'd like to write them to 4 columns, C - F, starting in row 2 until row 32.
Upvotes: 1
Views: 379
Reputation: 201378
I believe your goal as follows.
[current_price,forecast,demand,available_shares]
from the cell "C2" on the active sheet.For this, how about this answer?
for (i = 2; i < 33; i++) {}
every each stockId
. By this, the old value is overwritten by the next value. I think that this is the reason of your issue.[current_price,forecast,demand,available_shares]
to the array.By this flow, the value of each stockId
is put to the array, and then, the array is put to the Spreadsheet. When above points are reflected to your script, it becomes as follows.
function myFunction() {
let values = []; // Added
for (let stockId = 1; stockId < 32; stockId++) {
if (stockId == 24) continue;
var response = UrlFetchApp.fetch("https://api.torn.com/torn/" + stockId + "?selections=stocks&key=" + API);
var content = response.getContentText();
var json = JSON.parse(content);
var current_price = json["stocks"][stockId]["current_price"];
var forecast = json["stocks"][stockId]["forecast"];
var demand = json["stocks"][stockId]["demand"];
var available_shares = json["stocks"][stockId]["available_shares"];
values.push([current_price,forecast,demand,available_shares]); // Added
}
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Added
ss.getRange("C2:F" + (values.length + 1)).setValues(values); // Added
}
Upvotes: 1