Home > Back-end >  How to handle #Error in Google Sheets when a JSON property does not exist?
How to handle #Error in Google Sheets when a JSON property does not exist?

Time:04-26

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?

CodePudding user response:

Replace the line of code by

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

CodePudding user response:

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')");
  • Related