Skip to content

Instantly share code, notes, and snippets.

@thisdavej
Last active December 7, 2018 15:45
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 thisdavej/c587208b54dad8ab802439a98742a4c5 to your computer and use it in GitHub Desktop.
Save thisdavej/c587208b54dad8ab802439a98742a4c5 to your computer and use it in GitHub Desktop.
A modified version of the JSONTEMPLATE function from my post (https://thisdavej.com/consuming-json-web-data-using-google-sheets/) for Umar's JSON object
/**
* Parse JSON and render the results in a string template.
*
* @param {"http://path/to/myapi"} url
* JSON API data URL
* @param {"This is {{item1}}."} template
* string template for rendering results
* @customfunction
*/
function JSONTEMPLATE_UMAR(url, template) {
url = encodeURI(url);
var response = UrlFetchApp.fetch(url);
var obj = JSON.parse(response.getContentText());
if (!Array.isArray(obj)) {
obj = [obj];
}
// Handle for the shape of Umar's JSON object returned (as shown in mydata.json file in this gist)
var result = obj[0].result;
return result.map(function (row) {
return template.replace(/\{\{\s*(.*?)\s*\}\}/g, function (match, varName) {
return row[varName];
});
});
}
[
{
"result": [
{
"sg_event_id": "92-OndRfTs6fZjNdHWzLBw",
"timestamp": 1529618395,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click"
},
{
"sg_event_id": "bjMlfsSfRyuXEVy8LndsYA",
"timestamp": 1529618349,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click"
},
{
"sg_event_id": "fru_s2s1RtueuqBMNoIoTg",
"timestamp": 1529618255,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click",
"id": "555c1f7c5asdf7000167d87b"
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment