Google脚本和Alphavantage json查询:TypeError:无法读取属性

时间:2018-09-13 18:02:08

标签: google-apps-script alphavantage

我尝试使用以下代码从AlphaVantage股票市场API获取数据:

function importjson (){     
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("daily data");
   var day = new Date(),
      MILLIS_PER_DAY = 1000 * 60 * 60 *`enter code here` 24; 
   var urlvix = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=xlb&apikey=KEY",    responsevix = UrlFetchApp.fetch(urlvix),
      jsonvix = JSON.parse(responsevix);
// var date = jsonvix["Meta Data"]["3. Last Refreshed"];
   var yesterday = Utilities.formatDate(new Date(day.getTime() - MILLIS_PER_DAY), "GMT+1", "yyyy-MM-dd"),
      curdate  = Utilities.formatDate(new Date(), "GMT+1", "yyyy-MM-dd");
   var open = jsonvix["Time Series (Daily)"][curdate]["5. adjusted close"],
        close = jsonvix["Time Series (Daily)"][curdate]["1. open"],
        volumetoday = jsonvix["Time Series (Daily)"][curdate]["6. volume"],
        volumeyesterday = jsonvix["Time Series (Daily)"][yesterday]["6. volume"];
 // Logger.log(date);
  Logger.log(curdate);
  Logger.log(yesterday);
  if  (volumetoday > (volumeyesterday + volumeyesterday*1.1) ){
  Logger.log("distribution");
  }
  else {
  Logger.log("keine distribution")
  };
  Logger.log("open: " + open);
  Logger.log("close: " + close);
  Logger.log("Today´s volume: " + volumetoday);
  Logger.log("Yesterday´s volume: " + volumeyesterday);
  }

有时候我运行代码时会出现此错误:

TypeError: Cannot read property "2018-09-13" from undefined. (Zeile 17, Datei "Libary")

或者如果我使用var date = jsonvix["Meta Data"]["3. Last Refreshed"];

`TypeError: Cannot read property "["3. Last Refreshed"]" from undefined.` (Zeile 17, Datei "Libary")

Json就是这样:

Meta Data   
1. Information  "Daily Time Series with Splits and Dividend Events"
2. Symbol   "MSFT"
3. Last Refreshed   "2018-09-13 13:37:27"
4. Output Size  "Compact"
5. Time Zone    "US/Eastern"
Time Series (Daily) 
2018-09-13  
1. open "112.1200"
2. high "113.7250"
3. low  "112.1200"
4. close    "112.8050"
5. adjusted close   "112.8050"
6. volume   "14261782"
7. dividend amount  "0.0000"
8. split coefficient    "1.0000"

问题是,有时我每次运行代码时都不会出错,这使它有点不可靠。

此代码是否有市长问题?

谢谢

1 个答案:

答案 0 :(得分:1)

API并不总是返回您发布的JSON。有时它返回:

{ 
"Information":
"Thank you for using Alpha Vantage! Please visit https://www.alphavantage.co/premium/ if you would like to have a higher API call volume."
}

如您所见,这里没有["Meta Data"]["Time Series"]["2018-09-13"]键。唯一的键是["Information"]

因此,当您用完配额后,jsonvix["Meta Data"]将返回Undefined。您需要编写代码以使用Utilities.sleep()等待几秒钟后缓慢地进行呼叫和/或重新提取代码,或者使用AlphaVantage选择更高的音量。

参考文献: