Created
March 24, 2020 14:29
-
-
Save haggen/0e94caf8c3ccbeb36788fcfd5c024857 to your computer and use it in GitHub Desktop.
Simple IMPORTJSON function for Google Sheets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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