简体   繁体   English

javascript / node.js中的JSONP解析

[英]JSONP parsing in javascript/node.js

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? 如果我有一个包含JSONP响应的字符串,例如"jsonp([1,2,3])" ,并且想检索第三个参数3 ,我该如何编写一个为我做的函数? I want to avoid using eval . 我想避免使用eval My code (below) works fine on the debug line, but return undefined for some reason. 我的代码(如下)在调试行上工作正常,但由于某种原因返回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

More info: I'm running this in a node.js scraper, using request library. 更多信息:我正在使用request库在node.js刮板中运行它。

Here's a jsfiddle https://jsfiddle.net/bortao/3nc967wd/ 这是一个jsfiddle https://jsfiddle.net/bortao/3nc967wd/

Just slice the string to remove the jsonp( and ); 只需对字符串进行slice以删除jsonp(); , and then you can JSON.parse it: ,然后可以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 

Note that new Function is just as bad as eval . 请注意, new Functioneval一样糟糕。

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. 因为此函数不会返回,所以输出将是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM