提取函数'来自JSONP的JSON参数

Extract function's JSON argument from JSONP

本文关键字:JSONP JSON 参数 来自 函数 提取      更新时间:2023-09-26
我有一个json响应,里面有一个函数调用。解析后看起来像字符串
"foo({a: 5}, 5, 100)"

如何提取函数调用的第一个参数(在本例中为{a: 5}(?。

更新

这是来自服务器端的代码

var request = require('request')
  , cheerio = require('cheerio');
var url = 'http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=test&sl=en&tl=en';
request({url: url, 'json': true}, function(error, resp, body){
  console.log(typeof JSON.parse(body)); // => string
});

Google Dictionary API(未记录(使用JSONP,这并不是真正的JSON,因此您不能以您想要的方式在node.js中使用它(正如您在评论中所指出的(。您必须eval()响应。

注意查询参数如何具有callback=dict_api.callbacks.id100?这意味着返回的数据将像这样返回:dict_api.callbacks.id100(/* json here */, 200, null)

因此,您有两个选项:1:在代码中创建一个函数:

var dict_api = { callbacks: { id100: function (json_data) {
    console.log(json_data);
}};
request({url: url, 'json': true}, function(error, resp, body){
    // this is actually really unsafe. I don't recommend it, but it'll get the job done
    eval(body);
});

或者,您可以取下开始(dict_api.callbacks.id100((和结束(,200,null)[假设始终相同](,然后取下结果字符串JSON.parse()

request({url: url, 'json': true}, function(error, resp, body){
    // this is actually really unsafe. I don't recommend it, but it'll get the job done
    var json_string = body.replace('dict_api.callbacks.id100(', '').replace(',200,null)', '');
    console.log(JSON.parse(json_string));
});
foo({a: 5}, 5, 100);
function foo(){
    var the_bit_you_want = arguments[0];
    console.log(the_bit_you_want); 
}

很简单,在foo函数中使用以下内容:

arguments[0];