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.
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.
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);
}
}