Reading Data from API response - javascript

I'm trying to get specific data from a website API.
This is what I have, which just dumps the entire response into google sheets then I use mid to pull the correct string.
Is there a way to just return the value of "unpaid"?
Here is the response I get:
{"status":"OK","data":{"time":1612834200,"lastSeen":1612834035,"reportedHashrate":154783794,"currentHashrate":131055555.55555557,"validShares":116,"invalidShares":0,"staleShares":3,"averageHashrate":150218750,"activeWorkers":3,"unpaid":26075516667066776,"unconfirmed":null,"coinsPerMin":0.00000787562193181224,"usdPerMin":0.013755797534761213,"btcPerMin":2.9738348414523017e-7}}
All I want out of it is
"unpaid":26075516667066776
Below is the script I'm using to pull that data into google sheets.
function callNumbers() {
var response = UrlFetchApp.fetch("");
Logger.log(response.getContentText());
var data = response.getContentText();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(49,7).setValue([data]);
}
I can't seem to find much information on this, or I just don't know where to look. I got the above functions from a google page and then adapted them to pull the information from the website address that I wanted.
Thanks

I figured out that i had to change a few things. This what i ended up with.
function callNumbers() {
var response = UrlFetchApp.fetch("URL");
var var2 = JSON.parse(response.getContentText());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(49,7).setValue([var2.data.unpaid]);
Logger.log(var2.data.unpaid);
}

Related

How can I simply iterate through JSON that has a multileveled encapsulation with (Google) Javascript?

I want to retrieve the current prices of specific crypto currencies and update some fields in my google sheet.
Here a short codesnippet:
var api_url = "API-URL";
var response = UrlFetchApp.fetch(api_url);
var dataAll = JSON.parse(response.getContentText());
#When executing the URL in a Browser, I get this for dataAll:
dataAll content on Browser
#When executing it in the Google Script Editor, the Google Runtime Environment has this
dataAll content
#Here the rawdata response of the api-url call in JSON-Format with just 1 crypto entry in the data:
{"status":{"timestamp":"2021-04-01T21:11:59.721Z","error_code":0,"error_message":null,"elapsed":13,"credit_count":1,"notice":null,"total_count":4567},"data":[{"id":1,"name":"Bitcoin","symbol":"BTC","slug":"bitcoin","num_market_pairs":9477,"date_added":"2013-04-28T00:00:00.000Z","tags":["mineable","pow","sha-256","store-of-value","state-channels","coinbase-ventures-portfolio","three-arrows-capital-portfolio","polychain-capital-portfolio","binance-labs-portfolio","arrington-xrp-capital","blockchain-capital-portfolio","boostvc-portfolio","cms-holdings-portfolio","dcg-portfolio","dragonfly-capital-portfolio","electric-capital-portfolio","fabric-ventures-portfolio","framework-ventures","galaxy-digital-portfolio","huobi-capital","alameda-research-portfolio","a16z-portfolio","1confirmation-portfolio","winklevoss-capital","usv-portfolio","placeholder-ventures-portfolio","pantera-capital-portfolio","multicoin-capital-portfolio","paradigm-xzy-screener"],"max_supply":21000000,"circulating_supply":18670918,"total_supply":18670918,"platform":null,"cmc_rank":1,"last_updated":"2021-04-01T21:11:03.000Z","quote":{"CHF":{"price":55752.47839320199,"volume_24h":59267607529.77155,"percent_change_1h":0.02671823,"percent_change_24h":0.05924755,"percent_change_7d":11.47320017,"percent_change_30d":24.2882489,"percent_change_60d":81.38470939,"percent_change_90d":102.84247336,"market_cap":1040949952376.2463,"last_updated":"2021-04-01T21:11:15.000Z"}}}]}
For better readability I just pasted it into e.g. Notepad++ and went for Menu > JSON Viewer > Format JSON.
I know it's really basic, but how the heck can I now iterate through this encapsulated Object and dig to the appropriate level so I can read the price? I only want to pick a specific cryptocurrency, e.g. Ethereum which has id: 1027 and take its price for further purposes.
I want to be able to pick just the entries that fit to my portfolio (e.g. distinguish with id:) and take its price for a specific cell update in my google sheet.
Thanks a lot for your help in advance!
Best regards
Doniberi
if you want to get data by name just filter it
const api_url = 'API-URL';
const response = UrlFetchApp.fetch(api_url);
const dataAll = JSON.parse(response.getContentText());
const etherealData = dataAll.data.find(item => item.name === 'Ethereum');
function postDataToSheet() {
const ss=SpreadsheetApp.getActive();
const selected=['Symbol1','Symbol2']
const api_url = "API-URL";
let r= UrlFetchApp.fetch(api_url);
let rjson = r.getContentText();
let robj = JSON.parse(rjson);
let vs=[];
const ts=robj.status.timestamp;
const tc=robj.status.total_count;
vs.push(['TimeStamp',ts,'']);
vs.push('Total Count',tc,'');
vs.push(['Id','Symbol','Price']);
//***************************************************
//use this one to put them all on a sheet
robj.data.forEach((item,i)=>{
vs.push([item.id,item.symbol,item.quote.CHF.price])
});
const sh=ss.getSheetByName('Sheet1');
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
//***************************************************
//use this one to put only the selected on a sheet
robj.data.forEach((item,i)=>{
if(~selected.index(item.symbol)) {
vs.push([item.id,item.symbol,item.quote.CHF.price])
}
});
const sh=ss.getSheetByName('Sheet1');
sh.getRange(1,1,vs.length,vs[0].length).setValues(vs);
}
If you only need current price I'm pretty sure you can remove all the code and use something like =IMPORTDATA("https://cryptoprices.cc/BTC/") to fetch crypto prices.
No complex parsing, no authentication, no limitations.

How to pull data validation from another sheet in Google App Scripts

I'm trying to build a data validation for a cell from a range in a different sheet. I've tried the below code, and I continue to get this error "". Any help would be greatly appreciated.
function dataValidations(){
var builder = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Basic Info");
var invMgmt = SpreadsheetApp.openById("1eGNsJ2iB_IOzcfJe7DyFV_0WhzdQhvW2Lqdzfta2eV4");
var partners = invMgmt.getSheetByName("Partners and Locations").getRange(2,1,75,1).getValues();
var partnerRule = SpreadsheetApp.newDataValidation().requireValueInRange(partners).build();
var origin = builder.getRange("B4");
origin.setDataValidation(partnerRule);
}
In the case of requireValueInRange(range), range is the range object. In your script, the values retrieved by getValues() is 2 dimensional array. I think that this might be the reason of your issue. So in order to remove this issue, how about the following modification?
From:
var partners = invMgmt.getSheetByName("Partners and Locations").getRange(2,1,75,1).getValues();
var partnerRule = SpreadsheetApp.newDataValidation().requireValueInRange(partners).build();
To:
var partners = invMgmt.getSheetByName("Partners and Locations").getRange(2,1,75,1).getValues();
var partnerRule = SpreadsheetApp.newDataValidation().requireValueInList(partners.flat()).build(); // Modified
Note:
When SpreadsheetApp.openById("###").getSheetByName("###").getRange(###) is used for requireValueInRange, no error occurs and the retrieved values are the correct from other Spreadsheet. But when I confirmed the data validation in the cell, it is found that SpreadsheetApp.getActiveSpreadsheet() is used instead of SpreadsheetApp.openById("###"). So in this case, it seems that using requireValueInList is suitable.
References:
requireValueInRange(range)
requireValueInList(values)
flat()

I want to send email to user from API response in Javascript/ Google App Script?

I'm using a google apps script to get data from an external API. I was wondering if there is a way I can get the data from JSON sent to a user email on G-suite/Gmail after below code is executed. Anyone with ana idea on how to do this?
var url = 'https....';
var response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() === 200) {
var json = JSON.parse(response);
var id = json["id"];
sheet.getRange(2+i, 21).setValue(id);
sheet.getRange(2+i, 22).setValue(1);
}
else {
sheet.getRange(2+i, 22).setValue(2);
You can use one of both sendEmail functions, depending if you want the json to simply be in the body [1] or as an attached file [2]. A simple example would be:
GmailApp.sendEmail("mike#example.com", "current time", "The time is:");
[1] https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient,-subject,-body
[2] https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient,-subject,-body,-options

Unable to perform functions on google sheets data

I have a script that pulls in data from different endpoints from an API.
The script then puts the data in a google sheet. In this sheet I want to chart the data or perform a math/sum operation. I am able to do this with the data from one endpoint just fine. But the other endpoints (using the same code) does not allow me to do this. I can do =A1+A2 and the value will add. But if I try to do =sum(A1:A2) the result is 0. No matter what I do. I am able to do the sum() operation on the other endpoint. Its very peculiar.
Here is some of the code from my apps script:
var response = UrlFetchApp.fetch(requestUrl, params);
var json = JSON.parse(response.getContentText());
var rows = [], jsondata;
for (i = 0; i < json.length; i++) {
jsondata = json[i];
rows.push([jsondata.currency, jsondata.amount, jsondata.fee, jsondata.date]);
}
return rows;
}
Your problem is with number formats, change the cells by highlighting them go to 'Format' -> 'Number' -> 'Automatic' and then it will work with =SUM(A1:A2)
To fix this issue in your script, use .setNumberFormat('0') on the range to set the format you require. The number format may need to be '0.00' if you are working with decimals.

Appending new Google Sheets Data into BigQuery Table

So I'm new to all of this, both BigQuery and AppScript (coding in general..) and I'm learning as I go, so maybe to some my question may seem stupid. Please just hear me out.
I have created a script that loads 10 of the most recent data points into a Google Sheets doc from one of my BigQuery tables. Now, when I manually add new data points to the bottom of this table, I would like to have a load script run that uploads that new data back into BigQuery, and appends it to my original table. I read somewhere that just by inserting a new table the data is automatically appended if the table mentioned already exists. However, I haven't tested that part yet since I get stuck on an error earlier up the line..
Below is the load script I have loosely copied from https://developers.google.com/apps-script/advanced/bigquery
function loadCsv() {
var projectId = 'XX';
var datasetId = 'YY';
var tableId = 'daily_stats_testing';
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheet = file.getActiveSheet().getRange("A12:AK10000").getValues();
var data = sheet.getBlob().setContentType('application/octet-stream');
var job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1
}
}
};
job = BigQuery.Jobs.insert(job, projectId, data);
var Msg = "Load started. Check status of it here:" +
"https://bigquery.cloud.google.com/jobs/%s", projectId
Logger.log(Msg);
Browser.msgBox(Msg);
return;
}
Now the error I get (in a variety of forms, since I've been testing stuff out) is that the BigQuery.Jobs function only accepts Blob data, and that the data from my current sheet (with rage A12 marking the first manually imputed row of data) is not a Blob recognizable data set.
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
Does anyone have any recommendation on how to do this more efficiently?
Unfortunately the script has to load directly out of the current, open Spreadsheet sheet, since it is part of a larger script I will be running. Hopefully this isn't too much of a hinder!
Thanks in advance for the help :)
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
There is actually a function that does convert objects into blob type, namely newBlob(data).
To test this I got a range from my spreadsheet and used it.
function blobTest(){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:C1");
Logger.log(range); //here, range data is of type Range object
var blob = Utilities.newBlob(range);
Logger.log(blob); //here, range data is now of type Blob object
}

Categories

Resources