Created
April 24, 2018 13:10
-
-
Save brainysmurf/54fead65e0273a3d6523309be63c1d70 to your computer and use it in GitHub Desktop.
jsonp in google apps scripting
This file contains hidden or 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
/* | |
Suppose there is some endpoint that returns a jsonp to you, as in Google Visualization API | |
It gives you a text response that looks like this: | |
"some.namespace.nameOfFunction({obj:'blah'})" | |
We want the object inside that function call. | |
In a google app scripting context, we have no choice but to evaluate it the old-fashioned way, using "evil" eval(). | |
This solution builds a variable that resolves the namespace some.namespace.blah.blah and which ultimately becomes | |
a function that returns the passed parameter. | |
We build the variable with raw text, then eval it, giving the local context the ability to resolve the namespace and | |
call the function. | |
Then we are able to eval("some.namespace.nameOfFunction(...)") and get the original object | |
*/ | |
jsonp = function (callbackPath, responseText) { | |
var path, split, first, last, middle, buildEval, arr=[]; | |
split = callbackPath.split('.'); | |
first = split[0]; | |
middle = split.slice(1, split.length); | |
last = 'function (obj) { return obj; }'; // anonymous function that is always the value of the resolved path | |
arr[middle.length-1] = ''; // set up to do arr.join('}') which gives us our final braces | |
buildEval = 'var ' + first + ' = ' + middle.reduce( | |
function (acc, item, index) { | |
acc += '{"' + item + '": '; | |
return acc; | |
}, | |
'') + last + (middle.length > 0 ? '}' : '') + arr.join('}') + ';'; | |
eval(buildEval); | |
return eval(responseText); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment