IMPORTJSON自定义功能谷歌表

时间:2017-10-11 19:37:52

标签: json google-apps-script web-scraping google-sheets custom-function

/**
* Imports JSON data to your spreadsheet Ex: IMPORTJSON("http://myapisite.com","city/population")
* @param url URL of your JSON data as string
* @param xpath simplified xpath as string
* @customfunction
*/
function IMPORTJSON(url,xpath){

  try{
    // /rates/EUR
    var res = UrlFetchApp.fetch(url);
    var content = res.getContentText();
    var json = JSON.parse(content);

    var patharray = xpath.split("/");
    //Logger.log(patharray);

    for(var i=0;i<patharray.length;i++){
      json = json[patharray[i]];
    }

    //Logger.log(typeof(json));

    if(typeof(json) === "undefined"){
      return "Node Not Available";
    } else if(typeof(json) === "object"){
      var tempArr = [];

      for(var obj in json){
        tempArr.push([obj,json[obj]]);
      }
      return tempArr;
    } else if(typeof(json) !== "object") {
      return json;
    }
  }
  catch(err){
      return "Error getting data";  
  }

}

我在Google工作表中使用此自定义功能来尝试导入某些api数据。我已经把它做了一些事情,但是我很难把它搞砸了#id; id&#34;来自https://politicsandwar.com/api/alliances/(这是在单元格&#34; a1&#34;)

在我的工作表中的单元格中使用= importjson(A1,&#34; alliances / id&#34;),但它说的是节点不可用。

任何建议?

1 个答案:

答案 0 :(得分:0)

&#34;节点不可用的原因&#34; :

https://politicsandwar.com/api/alliances/检索的数据是JSON数据。 alliances是一个数组。当输入的xpath for(var i=0;i<patharray.length;i++){json = json[patharray[i]];}运行["alliances", "id"]时,我认为由于id中的密钥没有json.alliances,因此在第二个循环中发生错误。在您的脚本中,似乎无法分析JSON中的数组。

示例脚本:

如果您想使用https://politicsandwar.com/api/alliances/alliances/id检索数据,那么仅用于执行此操作的示例脚本如下所示。

function IMPORTJSON(url,xpath){
  var res = UrlFetchApp.fetch(url);
  var content = res.getContentText();
  var json = JSON.parse(content);
  var patharray = xpath.split("/");
  var res = [];
  for (var i in json[patharray[0]]) {
    res.push(json[patharray[0]][i][patharray[1]]);
  }
  return res;
}

如果数据显示不是您想要的,请随时告诉我。如果我误解了你的问题,我很抱歉。

相关问题