简体   繁体   中英

Extracting JSON values from Alpha Vantage API in Google Apps Script

I am trying to use Google Apps Script and Alpha Vantage APIs to extract JSON values to eventually be placed in Google Sheets. For certain Alpha Vantage API endpoints, I'm having trouble extracting the values I want.

Here is one of the JSON endpoints I want to work with:

https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey=demo

Note that this is just one of their demo links.

For this API I want to extract just the 'price' value.

{
"Global Quote": {
"01. symbol": "IBM",
"02. open": "128.9400",
"03. high": "130.9950",
"04. low": "127.7900",
"05. price": "130.0600",
"06. volume": "5835669",
"07. latest trading day": "2021-03-18",
"08. previous close": "129.0300",
"09. change": "1.0300",
"10. change percent": "0.7983%"
}
}

Another API I want to extract values from:

https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol=IBM&apikey=demo

What I have right now in the Google App Script editor is the very first step in this (new to JS), but not exactly where to go from here. The way the objects are named in the first API (eg "05. price") is throwing me off because I don't think I can use dot notation to call that value due to its naming convention in the API. (Let me know if that is incorrect).

function testAPI() {
  
  var api_url = "https://www.alphavantage.co/queryfunction=GLOBAL_QUOTE&symbol=IBM&apikey=demo";
  var json = UrlFetchApp.fetch(api_url);
  
  var obj = JSON.parse(json);
  
  Logger.log(obj);
}

Any help on this workflow is appreciated.

function testAPI() {
  var api_url = "https://www.alphavantage.co/queryfunction=GLOBAL_QUOTE&symbol=IBM&apikey=demo";
  var json = UrlFetchApp.fetch(api_url);
  var obj = JSON.parse(json);
  //I  assume everything above this is all correct if it's not that's your problem
  Logger.log(obj["Global Quote"]["05. price"]);
}

Testing:

function testAPI() {
  //var api_url = "https://www.alphavantage.co/queryfunction=GLOBAL_QUOTE&symbol=IBM&apikey=demo";
  //var json = UrlFetchApp.fetch(api_url);
  var json = '{"Global Quote": {"01. symbol": "IBM","02. open": "128.9400","03. high": "130.9950","04. low": "127.7900","05. price": "130.0600","06. volume": "5835669","07. latest trading day": "2021-03-18","08. previous close": "129.0300","09. change": "1.0300","10. change percent": "0.7983%"}}';
  var obj = JSON.parse(json);
  Logger.log(obj["Global Quote"]["05. price"]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM