Search code examples
javascriptgoogle-apps-scriptfinance

Calling a Key:Value pair in Google Apps Script is returning "Undefined" instead of the value


var api_key_id = '1234567890'
function open(ticker, date) {
  ticker="TSLA";
  date="2019-01-14";
  var url = "https://api.polygon.io/v1/open-close/" + ticker + "/" + date + "?apiKey=" + api_key_id;
  var response = UrlFetchApp.fetch(url);
  var data = response.getContentText();
  Logger.log(data);
}

When the above code is ran it logs this:

{"status":"OK","from":"2019-01-14T03:30:00Z","symbol":"TSLA","open":342,"high":343.3,"low":335.37,"close":338.93,"afterHours":336.2148,"volume":4425458}

But when I try to do this:

Logger.log(data.open);

The output is:

undefined

Is the "data" variable not actually an object? What am I missing?

EDIT: Solution Found: Parsing the result of getContentText() as JSON allowed the desired variable to be called, see below. Thanks to chuckx for pointing this out!

var api_key_id = '1234567890'
function open(ticker, date) {
  var url = "https://api.polygon.io/v1/open-close/" + ticker + "/" + date + "?apiKey=" + api_key_id;
  var response = UrlFetchApp.fetch(url);
  var data = response.getContentText();
  var json = JSON.parse(data);
  Logger.log(json.open);

Solution

  • HTTPResponse.getContextText() returns a string, so it is in fact not an object.

    Since this API returns JSON, you can parse the string using JSON.parse() and then interact with the returned object in the manner you're expecting.

    ...
    var apiResponse= JSON.parse(response.getContentText());
    Logger.log(apiResponse.open);