with the help of member / friend #Tanaike we were able to develop a code to import the data from a JSON list, but the data in the "price" field is imported as follows '16 .4700000000 'and I would like to import only the first 2 digits after the' . ' getting "16.47".
could you help me on this mission?
this is the current code I am using:
// Call the Bling API
var response = UrlFetchApp.fetch("https://bling.com.br/Api/v2/produtos/json&apikey=APIKEY?imagem=S&estoque=S");
//Logger.log(response.getContentText());
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
// Aquisição de dados.
var values = data.retorno.produtos.map(({produto: {codigo, gtin, descricao, preco, situacao}}) => [codigo, gtin, descricao, preco, situacao]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("produtos");
sheet.getRange(/*sheet.getLastRow() + */ 2, 1, values.length, values[0].length).setValues(values); ```
Here is a snippet from one of my projects where I set the number format as well as borders and background.
sheet.getRange(summaryAnnRetsFirstRow, 1, summaryAnnRetsLen, 4).setValues(summaryAnnRets);
sheet.getRange(summaryAnnRetsFirstRow,2, summaryAnnRetsLen, 2).setNumberFormat("$#,##0;$(#,##0)");
sheet.getRange(summaryAnnRetsFirstRow,4, summaryAnnRetsLen, 1).setNumberFormat("0.00%");
sheet.getRange(summaryAnnRetsFirstRow,1, summaryAnnRetsLen, sheet.getLastColumn()).setBorder(true, true, true, true, true, true, 'black', SpreadsheetApp.BorderStyle.SOLID_LIGHT);
sheet.getRange(summaryAnnRetsFirstRow,1, summaryAnnRetsLen, sheet.getLastColumn()).setBackground("#bdd4f9");
Related
I am trying to write code in Google Apps Script that will dump the data shown on the url https://coinmarketcap.com/ into a Google Sheet (say starting in A1). Not just data for one symbol, but all the symbols shown on this page. Specifically I am looking for the data for 'symbol' 'name' 'price' 'market_cap' .
The API documentation is here: https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest
I used to use an API connector to do this, but would rather a couple of lines of code. I spent a couple of hours reading about different approaches from search results, but they were either appropriate for a single symbol, or involved too many requests.
My code is below. I am not getting error, but it isn't returning any data either. I believe I need to tweak 'setValue' but am not sure how to do it.
Would appreciate any help. Thank you!
function coin_price() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Coins')
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank',
qs: {
start: '1',
limit: '5000',
convert: 'USD',
},
headers: {
'X-CMC_PRO_API_KEY': 'MY API KEY'
},
json: true,
gzip: true,
};
var url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank`;
var result = UrlFetchApp.fetch(url, requestOptions);
var txt = result.getContentText()
var d = JSON.parse(txt);
sheet.getRange(100,1).setValue(d.data.market_cap)
}
Suggestion
Perhaps you can try this tweaked script below:
Script:
function coin_price() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Coins')
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank',
qs: {
start: '1',
limit: '5000',
convert: 'USD',
},
headers: {
'X-CMC_PRO_API_KEY': 'API_Key'
},
json: true,
gzip: true,
};
var url = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?aux=cmc_rank`;
var result = UrlFetchApp.fetch(url, requestOptions);
var txt = result.getContentText()
var d = JSON.parse(txt);
var dSymbol = [];
var name = [];
var price = [];
var marketCap = [];
for(i=0; i<d.data.length; i++){
marketCap.push([d.data[i].quote.USD.market_cap]);
dSymbol.push([d.data[i].symbol]);
name.push([d.data[i].name]);
price.push([d.data[i].quote.USD.price])
}
//getRange structure (starting row, start col, total number of rows,total number of cols)
sheet.getRange(1,1,dSymbol.length,1).setValues(dSymbol); //Symbol in Col A (start col #1)
sheet.getRange(1,2,name.length,1).setValues(name); //Name in Col B (start col #2)
sheet.getRange(1,3,price.length,1).setValues(price); //Price in Col C (start col #3)
sheet.getRange(1,4,marketCap.length,1).setValues(marketCap); //Market Cap in Col D (start col #4)
}
Sample Result:
Reference:
getRange(row, column, numRows, numColumns)
setValues(values)
I am new to coding and have set myself a goal.
The goal has four parts:
Extract iOS Reminders from my iPhone using Shortcuts
Transform the resulting JSON file in Google Apps Script
Load the data into a table in Google Sheets
Present the reminders in an insightful way.
At this juncture, I can view the array in Google Apps Script using this code:
function getFileContent() {
var fileName = "Reminders.json";
var files = DriveApp.getFilesByName(fileName);
if (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var json = JSON.parse(content);
Logger.log(json);
}
}
My execution log returns the array in this format:
{reminders=[{list=Personal, task=Learn how to code, date=31 Dec 2021}, {...}, {...}, {...}]}
The notation "..." refers to additional reminders embedded in the array.
I need help using Google Apps Script to transform the JSON file into a table of data in Google Sheets.
Basically, you need to make a 2d-array from your JSON. It can be done this way:
var jsn = {'reminders':[
{'list':'Personal', 'task':'Learn how to code', 'date':'31 Dec 2021'},
{'list':'Personal', 'task':'Learn how to code', 'date':'32 Dec 2021'},
{'list':'Personal', 'task':'Learn how to code', 'date':'33 Dec 2021'},
]};
var array = jsn.reminders.map(x => [x.list, x.task, x.date]);
console.log(array);
Then you need to put the 2d-array on your sheet. Something like this:
function json_to_table() {
var jsn = {
'reminders': [
{ 'list': 'Personal', 'task': 'Learn how to code', 'date': '31 Dec 2021' },
{ 'list': 'Personal', 'task': 'Learn how to code', 'date': '32 Dec 2021' },
{ 'list': 'Personal', 'task': 'Learn how to code', 'date': '33 Dec 2021' },
]
};
var sheet = SpreadsheetApp.getActiveSheet();
// set table headers
var headers = [Object.keys(jsn.reminders[0])]; // get the keys from the first reminder
var range = sheet.getRange(1,1,1,headers[0].length);
range.setValues(headers); // put the keys into a first row of the table
// set table body
var body = jsn.reminders.map(x => [x.list, x.task, x.date]);
var range = sheet.getRange(2,1,body.length,body[0].length);
range.setValues(body);
}
Result:
Update
The full implementation could look like this:
function getFileContent() {
var files = DriveApp.getFilesByName("Reminders.json");
if (files.hasNext()) {
var json = JSON.parse(files.next().getBlob().getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
var headers = [Object.keys(json.reminders[0])];
var body = headers.concat(json.reminders.map(x => [x.list, x.task, x.date]));
sheet.getRange(1, 1, body.length, body[0].length).setValues(body);
}
}
I am very new to programming google app script, just trying to make some custom function. Sorry if this question is too basic...
I was following a tutorial to copy a table from Google Sheets into Google document but the exact same code the instructor was using did not worked for me.
I was getting this error:
Exception: The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable.
The simplified version of the code is:
function fun4(){
var ss = SpreadsheetApp.openById('17-23aFf6mN5oQrKNwNDy3Zh24_foTN5mXzNkjvd3V5w');
var sheet = ss.getSheets()[0];
var doc = DocumentApp.create('Sample Sheet Data');
var body = doc.getBody();
var numLines = sheet.getLastRow();
var numColumns = sheet.getLastColumn();
var rowData = sheet.getRange(1, 1, numLines, numColumns).getValues();
console.log(rowData);
var table = body.appendTable(rowData); // ERROR IN THIS LINE
table.getRow(0).editAsText().setBold(true);
}
After some search I found that the problem was caused by the last column containing Boolean values and changed .getValues() to .getDisplayValues().
It is working now but I am very confused...
How it was working in the instructor code but not in mine?
Why did not work if the output looks to be in the same format (double array?)
Code: (Gives an error when I append the table to doc , but worked in the instructor video)
var rowData = sheet.getRange(1, 1, numLines, numColumns).getValues();
console.log(rowData);
Output:
11:36:05 AM Info
[ [ 'NAME', 'EMAIL', 'AGE', 'ACTIVE' ],
[ 'Alex', 'alex#gmail.com', 50, true ],
[ 'Brian', 'brian#gmail.com', 34, false ],
[ 'Julian', 'julian#gmail.com', 42, true ],
[ 'John', 'john#gmail.com', 24, false ] ]
Code:
var rowData = sheet.getRange(1, 1, numLines, numColumns).getDisplayValues();
console.log(rowData);
Output:
11:36:05 AM Info
[ [ 'NAME', 'EMAIL', 'AGE', 'ACTIVE' ],
[ 'Alex', 'alex#gmail.com', '50', 'TRUE' ],
[ 'Brian', 'brian#gmail.com', '34', 'FALSE' ],
[ 'Julian', 'julian#gmail.com', '42', 'TRUE' ],
[ 'John', 'john#gmail.com', '24', 'FALSE' ] ]
I believe your goal as follows.
You want to know the reason the following situation.
After some search I found that the problem was caused by the last column containing Boolean values and changed .getValues() to .getDisplayValues().
It is working now but I am very confused... How it was working in the instructor code but not in mine? Why did not work if the output looks to be in the same format (double array?)
Answer:
About the error at the script of var rowData = sheet.getRange(1, 1, numLines, numColumns).getValues();, I thought that the reason of the issue might be due to using V8 runtime. Ref
When V8 runtime is enabled at the script editor, I confirmed that the error of The parameters (number[]) don't match the method signature for DocumentApp.Body.appendTable. occurred.
When V8 runtime is disabled at the script editor, I confirmed that no error occurred.
The table can be created using the value of var rowData = sheet.getRange(1, 1, numLines, numColumns).getValues(); and your sample values.
From your question, unfortunately, I cannot understand about the instructor video of Code: (Gives an error when I append the table to doc , but worked in the instructor video). But, above situation, I guess that the instructor video might not use V8 runtime.
So, in your script, when you want to test whether var rowData = sheet.getRange(1, 1, numLines, numColumns).getValues(); works, how about disabling V8 runtime at the script editor as follows and testing it again?
Reference:
V8 Runtime Overview
I've got the following script that pulls keys from the Poloniex JSON output, but doesn't put the actual data that corresponds to the keys into the actual sheet...it only puts the keys as titles at the top of the sheet.
I'm new to API's, and GAS, and coding in general, so I'm sure I'm missing something incredibly obvious, I'd really appreciate it if you could point out what.
Thanks in advance
function Bitcoin_fromPolo_toCSV() {
//Link the script with a spreasdsheet using the identifier found in the spreadsheet url
var ss = SpreadsheetApp.openById('1cubxxxxxxxxxxxxjDqM');
var APIPullSheet = ss.getSheetByName("APIPull");
// Clear Columns A,B,C,D
APIPullSheet.getRange('A2:D19999').clearContent();
var url = "https://poloniex.com/public?command=returnChartData¤cyPair=BTC_ETH&start=1502344800&end=9999999999&period=14400";
//Fetch pulls data from URL
var responseAPI = UrlFetchApp.fetch(url);
//Parse that JSON
var parcedData = JSON.parse(responseAPI.getContentText());
//Break that Parsed data into fields
//Define the 'stats' array, and populate it from the parced data pulled
// for loop iterates over each 'key' in 'parcedData' pushing that data to 'stats'
var stats = [];
stats.push(['date','high', 'low', 'open', 'close', 'volume', 'quoteVolume', 'weightedAverage']);
for(var key in parcedData.stats)
{
stats.push(parcedData.stats[key]);
}
statsRange = APIPullSheet.getRange(1, 1, stats.length, 8);
statsRange.setValues(stats);
}
How about the following modification?
Modification points :
JSON data from URL is as follows.
[
{
"date": 1502352000,
"high": 0.0899,
"low": 0.08754124,
"open": 0.08795499,
"close": 0.08988724,
"volume": 1390.47552953,
"quoteVolume": 15727.49124739,
"weightedAverage": 0.08841051
},
.
.
]
parcedData doesn't have stats as a key.
Flow for creating data :
Outer forEach() retrieves an element from parcedData.
Inner forEach() retrieves each key from stats[0], and retrieves data from the element of parcedData using the key.
Retrieved data is imported to temp which is 1 dimensional array.
The temp is imported to stats which is 2 dimensional array. After this, temp is initialized.
The script reflected this is as follows.
Modified script :
function Bitcoin_fromPolo_toCSV() {
var ss = SpreadsheetApp.openById('1cubxxxxxxxxxxxxjDqM');
var APIPullSheet = ss.getSheetByName("APIPull");
APIPullSheet.getRange('A2:D19999').clearContent();
var url = "https://poloniex.com/public?command=returnChartData¤cyPair=BTC_ETH&start=1502344800&end=9999999999&period=14400";
var responseAPI = UrlFetchApp.fetch(url);
var parcedData = JSON.parse(responseAPI.getContentText());
var stats = [];
stats.push(['date','high', 'low', 'open', 'close', 'volume', 'quoteVolume', 'weightedAverage']);
parcedData.forEach(function(e1){
var temp = [];
stats[0].forEach(function(e2){
temp.push(e1[e2])
});
stats.push(temp);
});
statsRange = APIPullSheet.getRange(1, 1, stats.length, 8);
statsRange.setValues(stats);
}
Result :
If I misunderstand your question, I'm sorry.
I am working on a Google Apps Script that links with a REST API and puts the data into a Google Sheet.
I have successfully done this once, but upon accessing some different data I get the error message
"The coordinates or dimensions of the range are invalid"
when they work perfectly fine on my other script. All data accessed is JSON so I am bit confused and is from the same source. The code I am using is:
function stats () {
var logIn = {
"Authorization" : "Basic " + Utilities.base64Encode("XXXX" + ':' + "XXXX")
};
var url = "XXXXX";
var params = {
"method":"GET",
"headers":logIn, };
var response = UrlFetchApp.fetch(url, params);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XXXX");
var dataAll = JSON.parse(response.getContentText()); //
var dataSet = dataAll;
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([XXXX]); //your JSON entities here
}
dataRange = sheet.getRange(1, 1, rows.length, 1);
dataRange.setValues(rows);
}
I have combined pieces of code from around the web and this works on my other script. The error appears on this line:
dataRange = sheet.getRange(1, 1, rows.length, 1);
I believe the issue is with the data I am accessing but I do not know how to alter the script for it to work.
The JSON data that works is shown like:
{
id: XXX,
group: XX,
text: "XXXX?",
creation_date: XXXX,
created_by: "XXXXX",
tags: [
"XXXX"
]
}
And the data that is causing the error is shown as:
{
2016-02-29: {
XXX: 0,
XXX: 0
},
I have had to 'XXXX' out a lot of the private information - apologies. Any help would be appreciated.
Javascript's length property is for indexed arrays and does not apply to Objects so dataSet.length returns undefined and the loop never executes.
To get the length of the object you can use Object.keys(dataSet).length as outlined here.