Skip to content

Instantly share code, notes, and snippets.

@haggen
Created March 24, 2020 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haggen/0e94caf8c3ccbeb36788fcfd5c024857 to your computer and use it in GitHub Desktop.
Save haggen/0e94caf8c3ccbeb36788fcfd5c024857 to your computer and use it in GitHub Desktop.
Simple IMPORTJSON function for Google Sheets.
/**
* Import data from a remote JSON document.
*
* @param {url} URL of the JSON document
* @param {path} dot notation path to the value you want to extract
*
* @return a single value extracted from the JSON.
*
* @customfunction
*/
function IMPORTJSON(url, path) {
Logger.log(url);
var cache = CacheService.getDocumentCache();
var data = cache.get(url);
if (!data) {
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() == 200) {
data = response.getContentText();
cache.put(url, data);
} else {
data = "null";
}
}
data = JSON.parse(data);
if (!data) {
return "";
}
path = path.split(".");
for (var i = 0, key = path[i], l = path.length; i < l; i++, key = path[i]) {
data = data[key];
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment