TypeError: Cannot read properties of undefined (reading '0')

Hi!

While trying to fetch Market Quote (Ticker Data and OHLC Data), I’m encountering a persistent “TypeError: Cannot read properties of undefined (reading ‘0’)” error, even after trying various approaches and meticulously checking the API documentation.

Here’s the relevant part of my code:

// ... other code ...

try {
  const response = UrlFetchApp.fetch(apiUrl, options);
  Logger.log(response.getContentText());
  const quoteData = JSON.parse(response.getContentText());
  Logger.log(quoteData);

  Logger.log(quoteData.data["nse_eq"])

  const outputData = [
    [quoteData.data["nse_eq"][0].last_price]
  ];

  sheet.getRange("B3").setValues(outputData);

} catch (error) {
  Logger.log("Error fetching or parsing LTP data: " + error);
}

// ... other code ...

The error seems to occur when trying to access the last_price property. I’ve verified that the API response contains data, and I used the correct endpoint and request structure.

Any help would be greatly appreciated!

Thanks!!!

Hello @Vivek_Raj

This might happen if the JSON parse is failing in formatting the data correctly. Can you try logging with below code:

try {
  const response = UrlFetchApp.fetch(apiUrl, options);
  Logger.log(response.getContentText());  // Log the raw response
  
  const quoteData = JSON.parse(response.getContentText());
  Logger.log(quoteData);  // Log the parsed JSON data
  
  // Check if 'nse_eq' exists and is an array with at least one item
  if (quoteData.data && quoteData.data["nse_eq"] && quoteData.data["nse_eq"].length > 0) {
    Logger.log(quoteData.data["nse_eq"][0]);  // Log the first item in 'nse_eq'

    const outputData = [
      [quoteData.data["nse_eq"][0].last_price]
    ];
    
    sheet.getRange("B3").setValues(outputData);
  } else {
    Logger.log("nse_eq is undefined or empty.");
  }

} catch (error) {
  Logger.log("Error fetching or parsing LTP data: " + error);
}

Can look into Raw Data and then help here.

Another thing, when using getContextText, you need to add exact value that you get as API response. You can try with below code, for NSE_EQ:

   // Check if NSE_EQ exists
  if (quoteData.data && quoteData.data["NSE_EQ"]) {
    for (let key in quoteData.data["NSE_EQ"]) {
      let nseEqPrice = quoteData.data["NSE_EQ"][key].last_price;
      Logger.log("NSE_EQ Price for key " + key + ": " + nseEqPrice);
   
    }
  } 

Hi @Hardik

“nse_eq” is undefined or empty even after trying both of your suggestions:

Here below is the code I am using after implementing both of your suggestions:

const accessToken = 'your_actual_access_token';
const clientId = 'your_actual_client_id';

function fetchLTP() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('Market Quotes');
  const instrumentId = '11536';

  const apiUrl = `https://api.dhan.co/v2/marketfeed/ltp`;

  const options = {
    'method': 'post',
    'headers': {
      'Accept': 'application/json',
      'access-token': accessToken,
      'client-id': clientId
    },
    'muteHttpExceptions': true,
    'payload': JSON.stringify({
      'nse_eq': [instrumentId]
    })
  };

  try {
    const response = UrlFetchApp.fetch(apiUrl, options);
    Logger.log(response.getContentText());
    const quoteData = JSON.parse(response.getContentText());
    Logger.log(quoteData);

    // Check if 'nse_eq' exists and is an array with at least one item
    if (quoteData.data && quoteData.data["nse_eq"] && quoteData.data["nse_eq"].length > 0) {
      Logger.log(quoteData.data["nse_eq"][0]);

      const outputData = [
        [quoteData.data["nse_eq"][0].last_price]
      ];

      sheet.getRange("B3").setValues(outputData);
    } else {
      Logger.log("nse_eq is undefined or empty.");

      // Check if NSE_EQ exists
      if (quoteData.data && quoteData.data["NSE_EQ"]) {
        for (let key in quoteData.data["NSE_EQ"]) {
          let nseEqPrice = quoteData.data["NSE_EQ"][key].last_price;
          Logger.log("NSE_EQ Price for key " + key + ":" + nseEqPrice);

        }
      }
    }

  } catch (error) {
    Logger.log("Error fetching or parsing LTP data: " + error);
  }
}

Eagerly looking forward to your response…

Wish you a good day!

Hello @Vivek_Raj

Do note that this is ENUM string, and has to be NSE_EQ in caps, not in smallcase.

Also, same would be required here:

Try with all caps NSE_EQ here.

1 Like