1

我有一个 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
});
4

3 回答 3

2
foo({a: 5}, 5, 100);

function foo(){
    var the_bit_you_want = arguments[0];
    console.log(the_bit_you_want); 
}
于 2013-02-08T02:19:06.540 回答
2

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

arguments[0];
于 2013-02-08T02:19:39.363 回答
2

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));
});
于 2013-02-08T02:29:28.557 回答