【问题标题】:JSONP parsing in javascript/node.jsjavascript/node.js 中的 JSONP 解析
【发布时间】:2019-01-04 03:50:40
【问题描述】:

如果我有一个包含 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

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

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

【问题讨论】:

  • 回答为什么它返回 undefined ... 因为 'jsonp([1,2,3]);' 应该是 'return jsonp([1,2,3]);' - 如果您希望函数返回值,则需要从函数返回值
  • 进一步了解@JaromandaX 所说的:var f = new Function("jsonp", "return " + jsonp);
  • 要么或@nnnnnn 相同的结果:p 啊,是的,但我知道区别 - 好皮卡
  • 当然@JaromandaX,但我认为j 变量代表刮板实用程序,因此将return 部分包含在unwrap() 中并与该字符串分开是有意义的。
  • 是的,正如我所说,我现在明白即使最终结果相同,这也更有意义:p

标签: javascript json node.js web-scraping jsonp


【解决方案1】:

只要把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 一样糟糕。

【讨论】:

  • 但 op 期待 3 作为输出:p
【解决方案2】:

只需稍作改动,就可以正常工作:

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

不返回你的匿名函数是这样的:

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

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

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 2014-02-02
    • 2016-04-23
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多