Concatenate a variable into a JSON call with Google Sheets - javascript

I'm making an API call to coinmarket cap and looping through a range, in a Google spreadsheet of crypto tickers.
The code is as follows:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
var r = sheet.getRange('B2:B17').getValues();
for (var i = 0; i < r.length; i++) {
symbol = r[i][0];
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=' + symbol + '&convert=USD&CMC_PRO_API_KEY=8192e0b9-fda4-4668-9251-3dfded3bdc2f';
//url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD&CMC_PRO_API_KEY=abcdetc'
var resp = UrlFetchApp.fetch(url);
var result = JSON.parse(resp.getContentText());
var price = result.data.BTC.quote.USD.price;
sheet.getRange(2 + i, 3).setValue(price);
This works but it provides, obviously, only the price for Bitcoin because BTC is in the var price line.
Instead of BTC I want to have + symbol + so that the code can loop through all the different symbols. I have tried this:
var price = result + "." + data + "." + symbol + "." + quote + "." + USD + "." price
This does not work. I have tried other various uses of "" which were also unsuccessful and also attempted to concatenate string separately.
How can this be done correctly?
Thank you in advance!

You may try something like this:
string.concat(string1, string2, ..., stringX)
or
var arr = ['a1', 'b1', 'c1'];
console.log(arr.join(',')); // 'a1,b1,c1'.
Explicit typecast can be done as,
var price = ([String(result), String(data), String(symbol), String(quote), String(USD), String(price)]).join(".")

var price = result.data.BTC.quote.USD.price;
Should be replaced with a similar code that covers your variable name:
var price = result.data[symbol].quote.USD.price;

Related

Increment ID from last row google apps script

I coded something for google apps script. It is to increment ID +1 based on the last row. Everything is working so far except for the numbering of the new ID, instead of appearing as a number.
The result appears as R-NaN instead of R-002 or something similar
What do you think should I revise in my code? Thank you.
function new_item() {
// Get current spreadsheet
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var mysheet = ss.getActiveSheet();
// Set date to today in update field at the top of the sheet
var now = new Date();
mysheet.getRange(1,4).setValue(now);
// Last non-empty row
var rlast = mysheet.getLastRow();
Logger.log("Last row = " + rlast);
// Insert Row below
mysheet.insertRows(rlast+1);
var r = rlast+1;
// Copy format from row above
var sourcerange = mysheet.getRange(rlast + ":" + rlast);
var targetrange = mysheet.getRange(r + ":" + r);
sourcerange.copyTo(targetrange, {formatOnly:true});
// Col. 2 : Risk identity
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = riskid.substring(1,riskid.length);
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb
// Write risk nb i.e. "R004"
mysheet.getRange(r,2).setValue("R-"+ s.substring(s.length-4))
}
``´
Explanation / Issue:
Your code really depends on the value of the cell in column B last row:
var riskid = mysheet.getRange(rlast,2).getValue();
There are two scenarios but I believe the second applies to your issue:
If the value in the cell is a number (e.g. 35233) then riskid will be an integer and therefore riskid.length will return null and as a result the if condition will evaluate to false. In this case, you can either use getDisplayValue or toString() instead to get the number as string and then you can apply .length to it:
var riskid = mysheet.getRange(rlast,2).getValue();
If the value in the cell is a string (e.g. R112) then the if condition will evaluate to true. If you do that:
var riskidnb = riskid.substring(1,riskid.length);
riskidnb will be 112 but this is still a string and therefore if you do riskidnb++ you will get NAN like the issue you have right now. In order to fix that, convert riskidnb to integer:
var riskidnb = parseInt(riskid.substring(1,riskid.length));
then you can do riskidnb++ and finally convert it back to string:
var s = "000" + riskidnb.toString();
Solution:
function new_item() {
// Get current spreadsheet
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var mysheet = ss.getActiveSheet();
// Set date to today in update field at the top of the sheet
var now = new Date();
mysheet.getRange(1,4).setValue(now);
// Last non-empty row
var rlast = mysheet.getLastRow();
Logger.log("Last row = " + rlast);
// Insert Row below
mysheet.insertRows(rlast+1);
var r = rlast+1;
// Copy format from row above
var sourcerange = mysheet.getRange(rlast + ":" + rlast);
var targetrange = mysheet.getRange(r + ":" + r);
sourcerange.copyTo(targetrange, {formatOnly:true});
// Col. 2 : Risk identity
var riskid = mysheet.getRange(rlast,2).getValue();
if (riskid.length > 3){
// Extract number ex. 3
var riskidnb = parseInt(riskid.substring(1,riskid.length));
// Increase risk number +1
riskidnb++
// Convert to string "0004"
var s = "000" + riskidnb.toString();
// Write risk nb i.e. "R004"
mysheet.getRange(r,2).setValue("R-"+ s.substring(s.length-4))
}
}
Output:

Renaming/Modifying using current name in javascript

I am new to javascript, i tried to modify a text shown below with substring command.
eg. "ABCD_X_DD_text" into "ABCD-X(DD)_text" this
i used this
var str = "ABCD_X_DD_cover";
var res = str.substring(0,4)+"-"+str.substring(5,6)+"("+str.substring(7,9)+")"+str.substring(9,15);
// print to console
console.log(res);
i got what i want. But problem is X and DD are numerical (digit) value. and they are changeable. here my code just stop working.
it can be ..... "ABCD_XXX_DDDD_text" or "ABCD_X_DDD_text".
could you suggest some code, which works well in this situation.
You can use a split of the words.
var strArray = [
"ABCD_X_DD_cover",
"ABCD_XX_DD_cover",
"ABCD_XXX_DD_cover"
];
for(var i = 0; i < strArray.length; i++){
var split = strArray[i].split("_");
var str = split[0] + "-" + split[1] + "(" + split[2] + ") " + split[3];
console.log(str);
}
I used a for cycle using an array of strings, but you can do it with a variable too.

Cannot read properly "split"

I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.

How to get the Last Value from Cookie with 2 variables inside Using split() methode in javascript

I have cookie that consist of 2 variables. I want to get the value from the variable #2 (the last one) But I don´t know how to deal with that.
From PHP
I have set cookie like this :
setcookie ('mysite'.$user_id,'user_id='. $user_id. '&msg_id='. $c_id, time() + $cookie_time);
What I'm trying to get is the value of msg_id
In javascript
var ca="mysite"+user_id;
ca = new Array();
ca = document.cookie.split(';');
for (var w in ca)
NmeVal = new Array();
NmeVal = ca[w].split('=');
But how can I get just only the value of msg_id as I mentioned above?
UPDATE
I got it to work now by doing this:
var NmeVal = new Array();
NmeVal = ca[w].split('=');
var vl =unescape(NmeVal[1]);
var gala = vl.split('=');
alert(gala[2]);
I get the only value I want::
it work in IE, FIrefox, Chrome
But why didn´t it work in Safari ?
UPDATE # FINAL
Finally I found the solution jquery.cookie.js
Only 3 lines work and the job is done !!!
Create - get - delete cookie like crazy and the plugin is not that big file like other packages.
And because of this plug in I start to use cookie like crazy now :)
You are better of storing information in cookies this way:
setcookie("user_id", $user_id);
setcookie("msg_id", $c_id);
// ...
Javascript function for getting the cookie value by giving a name:
var user_id = getCookie("user_id");
function getCookie(name) {
var result = "";
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1) {
startOfCookie += searchName.length;
endOfCookie = myCookie.indexOf(";", startOfCookie);
result = unescape(myCookie.substring(startOfCookie, endOfCookie));
}
return result;
}
When you are parsing a cookie, parse from the outside in.
One thing I found when parsing the cookie you posted was an additional space before 'mysite'. Using the console and logging the results of each step can help you find small issues like that.
Split first by ','
loop and split by '='
unescape value to the right of the '='
Then in your case, loop and split by '&'
This routine should work for you ([Fiddle][5]):
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
function parseCookie(cookie) {
var vals = cookie.split(',');
var nameValue = {}, cur, mysite;
for (var i = 0; i < vals.length; ++i) {
cur = vals[i].split('=');
nameValue[cur[0].trim()] = unescape(cur[1]);
}
mysite = nameValue.mysite.split('&');
nameValue.mysite = {};
for (i = 0; i < mysite.length; ++i) {
cur = mysite[i].split('=');
nameValue.mysite[cur[0].trim()] = cur[1];
}
return nameValue;
}
var cookie = "PHPSESSID=oleGInunYQIP7QSLpDUVR3, mysite=usr%3DChrome%26hash%3D594f803b380a41396ed63dca39503542";
console.log(JSON.stringify(parseCookie(cookie)));
Result:
{"PHPSESSID":"oleGInunYQIP7QSLpDUVR3","mysite":{"usr":"Chrome","hash":"594f803b380a41396ed63dca39503542"}}
You can retrieve any value you need by something like:
var usr = result.mysite.usr;

Javascript string manipulation url

My problem is I am trying to extract certain things from the url. I am currently using
window.location.href.substr()
to grab something like "/localhost:123/list/chart=2/view=1"
What i have now, is using the index positioning to grab the chart and view value.
var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);
But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?
var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];
Of course you may want to add in some validation checks before using the outcome of the match.
Inspired by Paul S. I have written a function version of my answer:
function getPathVal(name)
{
var path = window.location.pathname;
var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
var data = path.match(regx);
return data[1] || null;
}
getPathVal('chart');//2
Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI
Here's a way using String.prototype.indexOf
function getPathVar(key) {
var str = window.location.pathname,
i = str.indexOf('/' + key + '=') + key.length + 2,
j = str.indexOf('/', i);
if (i === key.length + 1) return '';
return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');
You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:
var x = "/localhost:123/list/chart=2/view=1";
var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
var part = spl[i];
var index = part.indexOf("=");
if (index > 0) {
res[part.substring(0, index)] = part.substring(index + 1);
}
}
console.log(res);
// res = { chart: 2, view: 1}
FIDDLE

Categories