javascript/node.js 中的 JSONP 解析

JSONP parsing in javascript/node.js

如果我有一个包含 JSONP 响应的字符串,例如 "jsonp([1,2,3])",并且我想检索第三个参数 3,我该如何编写一个函数来为我执行此操作?我想避免使用 eval。我的代码(下方)在调试行上运行良好,但由于某些原因 return undefined

  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

更多信息:我在 node.js 爬虫中 运行 使用 request 库。

这是一个 jsfiddle https://jsfiddle.net/bortao/3nc967wd/

只需将slice字符串去掉jsonp();,然后就可以JSON.parse了:

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

请注意 new Functioneval 一样糟糕。

稍作改动即可正常工作:

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

没有 return 你的匿名函数是这样的 :

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

因为这个函数没有 return 所以输出将是未定义的。