2

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/

5
  • 1
    to answer why it returns undefined ... because 'jsonp([1,2,3]);' should be 'return jsonp([1,2,3]);' - you need to return values from functions if you want functions to return values Commented Jul 27, 2018 at 4:47
  • 1
    Further to what @JaromandaX said: var f = new Function("jsonp", "return " + jsonp); Commented Jul 27, 2018 at 4:50
  • either or @nnnnnn same result :p ahh, yes, but I know the difference - good pickup Commented Jul 27, 2018 at 4:51
  • Sure @JaromandaX, but I figured the j variable was standing in for the scraper utility so it would make sense to have the return part within the unwrap() and separate to that string. Commented Jul 27, 2018 at 4:53
  • yep, as I said, I see now how that makes more sense even though the end result is identical :p Commented Jul 27, 2018 at 4:53

2 Answers 2

4

Just slice the string to remove the jsonp( and );, and then you can JSON.parse it:

function unwrap(jsonp) {
  return JSON.parse(jsonp.slice(6, jsonp.length - 2));
}

var j = 'jsonp([1,2,3]);'

console.log(unwrap(j)); // returns the whole array
console.log(unwrap(j)[2]); // returns the third item in the array

Note that new Function is just as bad as eval.

Sign up to request clarification or add additional context in comments.

1 Comment

but op was expecting 3 as the output :p
1

Just a little changes and it'll work fine:

function unwrap(jsonp) {
    var f = new Function("jsonp", `return ${jsonp}`);
    console.log(f.toString())
    return f(unwrapper);
}

function unwrapper(param) {
    console.log(param[2]); // This works!
    return param[2];
}

var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined

without return your anonymous function is like this :

function anonymous(jsonp) {
    jsonp([1,2,3]);
}

because this function doesn't return so the output will be undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.