Google scripts and Alphavantage json query: TypeError: Cannot read property

Google scripts and Alphavantage json query: TypeError: Cannot read property

我尝试使用以下代码从 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"

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

这段代码有什么大问题吗?

谢谢

API 并不总是 return 您发布的 JSON。有时 returns:

{ 
"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"] 将 return Undefined。您需要编写代码以缓慢地进行调用 and/or 使用 Utilities.sleep() 等待几秒钟后重新获取,或者使用 AlphaVantage 选择更高的音量。

参考文献: