IMPORTJSON custom function google sheets

百般思念 提交于 2020-01-06 05:10:46

问题


/**
* 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";  
  }

}

I'm using this custom funcation in a google sheet to try and import certain api data. I've gotten it to do some things but im having trouble getting it to pul the "id" from https://politicsandwar.com/api/alliances/ (this is in cell "a1")

In the cell in my sheet im using =importjson(A1, "alliances/id") but all it says is node not available.

Any Suggestions?


回答1:


Reason of "Node Not Available" :

Data retrieved from https://politicsandwar.com/api/alliances/ is JSON data. alliances is an array. When for(var i=0;i<patharray.length;i++){json = json[patharray[i]];} is run by the inputted xpath ["alliances", "id"], I think that an error occurs at 2nd loop because of no id of the key in json.alliances. In your script, it seems that arrays in JSON cannot be analyzed.

Sample script :

If you want to retrieve data from https://politicsandwar.com/api/alliances/ using alliances/id, the sample script only for doing it is as follows.

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;
}

If the display of data is not what you want, feel free to tell me. If I misunderstand your question, I'm sorry.



来源:https://stackoverflow.com/questions/46696207/importjson-custom-function-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!