首页 > 解决方案 > javascript/node.js 中的 JSONP 解析

问题描述

例如,如果我有一个包含 JSONP 响应的字符串"jsonp([1,2,3])",并且我想检索第三个参数3,我该如何编写一个函数来为我做这件事?我想避免使用eval. 我的代码(如下)在调试行上运行良好,但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

更多信息:我正在使用request库在 node.js 刮板中运行它。

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

标签: javascriptjsonnode.jsweb-scrapingjsonp

解决方案


只需slice删除jsonp(and的字符串);,然后您就可以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.


推荐阅读