IMPORTJSON custom function google sheets

2019-03-05 17:30发布

/**
* 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条回答
老娘就宠你
2楼-- · 2019-03-05 17:55

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.

查看更多
登录 后发表回答