我想從API輸出創建數組。然後將數組過濾爲itemID指定的一個項目。以下是我的嘗試。我收到一個錯誤,jsonArray不存在於函數測試中。我認爲我需要把它變成一個全球變量或某種東西,但那是我撞牆的地方。JSON數組的創建和過濾
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;
}
我以前有它用下面的代碼(從別人撕開)工作,但此功能在每次使用打了一個電話。我試圖減少每次刷新刷新一次調用的次數(這是在谷歌文檔腳本管理器中)。
// 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;
}
完美,你讀了我的心!對不清楚的問題抱歉,因爲我的JavaScript是相對綠色,並且是深夜! :)我使用您建議的緩存服務使用其他代碼更新了我的問題。 –
好的,而不是篩選它,我可以只抓取一部分,因爲我只需要Min_Sale_Unit_Price。正確?對不起關於所有的帽子,我的電話Autocaps一切,我不能阻止它。 –
是的 - 限制內容只是你需要的位將有所幫助。 – Mogsdad