If I have an string containing a JSONP response, for example"jsonp([1,2,3])", and I want to retrieve the 3rd parameter 3, how could I write a function that do that for me? I want to avoid using eval. My code (below) works fine on the debug line, but return undefined for some reason.
function unwrap(jsonp) {
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var f = new Function("jsonp", jsonp);
return f(unwrapper);
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
More info: I'm running this in a node.js scraper, using request library.
Here's a jsfiddle https://jsfiddle.net/bortao/3nc967wd/
'jsonp([1,2,3]);'should be'return jsonp([1,2,3]);'- you need to return values from functions if you want functions to return valuesvar f = new Function("jsonp", "return " + jsonp);jvariable was standing in for the scraper utility so it would make sense to have thereturnpart within theunwrap()and separate to that string.