/**
* 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?
Reason of "Node Not Available" :
Data retrieved from
https://politicsandwar.com/api/alliances/
is JSON data.alliances
is an array. Whenfor(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 noid
of the key injson.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/
usingalliances/id
, the sample script only for doing it is as follows.If the display of data is not what you want, feel free to tell me. If I misunderstand your question, I'm sorry.