【发布时间】:2021-02-26 01:35:29
【问题描述】:
当我尝试在我的 Google 表格上调用 hello() 时,它返回
错误类型错误:无法读取属性 '5。未定义的汇率'(第 50 行)。
还设置了 Apps 脚本的触发器
| Criteria | set |
|---|---|
| Choose which function to run | hello |
| Which runs at deployment | head |
| Select event source | From spreadsheet |
| Select event type | On Open |
| Failure notification settings | Notify me Daily |
JSON 对象
{
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "SGD",
"4. To_Currency Name": "Singapore Dollar",
"5. Exchange Rate": "1.32783000",
"6. Last Refreshed": "2021-02-26 01:28:59",
"7. Time Zone": "UTC",
"8. Bid Price": "1.32783000",
"9. Ask Price": "1.32783000"
}
}
Google 应用脚本函数
function hello(){
var usdCurrency = "USD";
var AV_API_Key = "KEYS";
var sgdCurrency = "SGD"
var url = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=" + usdCurrency + "&to_currency=" + sgdCurrency + "&apikey=" + AV_API_Key;
var response = UrlFetchApp.fetch(url);
var result = JSON.parse(response.getContentText());
var currencyPrice = result["Realtime Currency Exchange Rate"]["5. Exchange Rate"];
Logger.log(currencyPrice); // 1.32794000
Logger.log(typeof(currencyPrice)); // String
return currencyPrice;
}
更新
我设置了一个名为jsonObj的预定义变量,它能够获取对象中的项目并将其放置在谷歌表格中。
function initTesting(){
var jsonObj = {
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "SGD",
"4. To_Currency Name": "Singapore Dollar",
"5. Exchange Rate": "1.32783000",
"6. Last Refreshed": "2021-02-26 01:28:59",
"7. Time Zone": "UTC",
"8. Bid Price": "1.32783000",
"9. Ask Price": "1.32783000"
}
};
var getPrice = jsonObj["Realtime Currency Exchange Rate"]["5. Exchange Rate"];
return getPrice;
}
【问题讨论】:
标签: javascript json rest google-apps-script alpha-vantage