I'm trying to call data from Coin Market Cap to a Google sheet via Apps Script. I don't understand the TypeError I'm doing here.
Here is the code:
function getCryptoPrice() {
var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EPS data CMC");
var url="https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol=BTC"
var requestOptions = {
method: 'GET',
uri: 'https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest',
qs: {
start: 1,
limit: 5000,
convert: 'USD'
},
headers: {
'X-CMC_PRO_API_KEY': '***********hidden*************'
},
json: true,
gzip: true
};
var httpRequest= UrlFetchApp.fetch(url, requestOptions);
var getContext= httpRequest.getContentText();
var parseData=JSON.parse(getContext);
sh1.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
}
And the error:
TypeError: Cannot read property 'USD' of undefined
getCryptoPrice @ Code.gs:24
Keywords : google sheet, apps script, coin market cap, quote, latest, V2, api,
CodePudding user response:
You're getting that error because parseData.data.BTC
is returning an array
.
Try changing this to:-
sh1.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
this
sh1.getRange(1, 2).setValue(parseData.data.BTC[0].quote.USD.price)