我想从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