javascript - 从 JSONP 中提取函数的 JSON 参数

标签 javascript json node.js

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

关于javascript - 从 JSONP 中提取函数的 JSON 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764625/

相关文章:

javascript - ExtJS 仅编辑网格单元格是新的

javascript - 防止 SVG 元素在浏览器窗口大小调整时缩放

python - CSV 到 JSON,从列创建数组

jquery - 使用jquery忽略JSON调用中的部分键

javascript - 在 Jade 文件中使用 Ajax 返回值

javascript - 在 NodeJS 中获取数组值时出现问题

javascript - 解析时间变量

javascript - 返回异步数据然后在 Node.js 中同步导出

java - 将 JSON 添加到 spring rest Controller 中的模型时如何删除转义字符

javascript - 为什么我的中间件执行了两次?