简体   繁体   中英

How to handle #Error in Google Sheets when a JSON property does not exist?

I am using the following script in Google Sheets to retrieve certain company (retresented by ticker symbol) properties (in JSON) from Yahoo.Finance and present them in adjacent cells in the sheet.

I am retrieving 3 properties; this list will be expanded in the future. I am currently trying to achieve proper error-handling.

 function yahooFinance(symbol) {
  const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(symbol)
    + '?modules=price,assetProfile,summaryDetail,incomeStatementHistory,'
    + 'balanceSheetHistory,defaultKeyStatistics,financialData,calendarEvents,'
    + 'recommendationTrend,upgradeDowngradeHistory,majorHoldersBreakdown'
    ;
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  const responseCode = response.getResponseCode();
  if (responseCode === 200) {
    const quote = JSON.parse(response.getContentText());
    const summaryDetail = quote.quoteSummary.result[0].summaryDetail;

    const divYield = summaryDetail.dividendYield.fmt  || "-";
    const payoutRatio = summaryDetail.payoutRatio.fmt || "-";
    const marketCap = summaryDetail.marketCap.fmt     || "-";

    return [[ divYield , payoutRatio, marketCap ]];
  }
  else {
    return "-";
  }
}

The problem is: if a certain property does not exist for a certain symbol, Google Sheets returns an error: #Error TypeError: Cannot read property 'marketCap' of undefined (line 43).

My question is: how can I still return a - (hyphen) in this case?

Replace the line of code by

const marketCap = summaryDetail.marketCap == null ? '-' : summaryDetail.marketCap.fmt;

Consider set a formula to the cell where you're binding the value.

Example adapted from this answer :

var cell = sheet.getRange("B5");
cell.setFormula("=IFNA(B5,'Invalid value')");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM