我正在尝试从 API 输出创建数组。然后将数组过滤到 itemID 指定的一项。下面是我的尝试。我收到一个错误,即函数测试中不存在 jsonArray。我想我需要把它变成一个全局变量或其他东西,但这就是我碰壁的地方。
function onOpen() {
var myUrl = "http://www.gw2spidy.com/api/v0.9/json/all-items/all"
var jsonData = UrlFetchApp.fetch(myUrl);
var jsonArray = JSON.Parse(jsonData);
return jsonArray
}
function test(itemID) {
var jsonFilter = jsonArray.filter(function(itemID){return itemID.data_id==itemID});
var jsonObject = JSON.parse(jsonFilter).result;
var adjustedValue = (jsonObject.min_sale_unit_price / 100);
return adjustedValue;
}
我以前使用以下代码(从其他人那里摘录)使用它,但是每次使用该函数都会进行调用。我正在尝试将每次工作表刷新的调用次数减少到一次调用(这是在 google docs 脚本管理器中)。
// function to return the current sell value for an item (designated by
// the item’s ID number) from GW2Spidy's API formatted with copper in
// the tens and hundreds places
function getItemSellValue(itemID) {
// base URL for the API that will return JSON for the itemID supplied
var myUrl = "http://www.gw2spidy.com/api/v0.9/json/item/" + escape(itemID);
// fetches the information from the URL in an HTTPResponse
var jsonData = UrlFetchApp.fetch(myUrl);
// now we convert that response into a string so that we can use it
var jsonString = jsonData.getContentText();
// now, we turn it into a Javascript object for easier handling
// *note: I also remove the "result" wrapper object so we can
// use direct calls on the objects parameters
var jsonObject = JSON.parse(jsonString).result;
// now I divide the value by 100 in order to format it more like
// currency. (ie. 126454, which equals 12 gold, 64 silver,
// and 54 copper will now be displayed as
// 1264.54)
var adjustedValue = (jsonObject.min_sale_unit_price / 100);
// finally we return the adjusted min sell value
return adjustedValue;
}
更新
我更新了删除 onOpen() 并切换到缓存服务的代码。我现在收到以下错误:“错误:参数太大:值(第 12 行,文件“gwspidy api”)”。第 12 行是cache.put("gw2spidy-data", jsonData, 1500);
数据的大小吗?不知道能过滤多少。完整代码如下。
function test(itemID) {
var cache = CacheService.getPublicCache();
var cached = cache.get("gw2spidy-data");
// check if the data is cached and use it if it is
if (cached != null) {
var jsonData = cached
}
//otherwise fetch the data and cache it
else {
var myUrl = "http://www.gw2spidy.com/api/v0.9/json/all-items/all"
var jsonData = UrlFetchApp.fetch(myUrl);
cache.put("rss-feed-contents", jsonData, 1500);
}
//put data into an array and filter the result down to the given id, then return the function value
var jsonArray = JSON.Parse(jsonData);
var jsonFilter = jsonArray.filter(function(itemID){return itemID.data_id==itemID});
var jsonObject = JSON.parse(jsonFilter).result;
var adjustedValue = (jsonObject.min_sale_unit_price / 100);
return adjustedValue;
}