提取函数'来自JSONP的JSON参数
Extract function's JSON argument from JSONP
我有一个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];
相关文章:
- 如何使用jquery ajax和jsonp在您自己的域上读取json数据
- 分析angular.js中的JSONP$http.json()响应
- 如何使用Angular$http.jsonp从S3加载JSON文件
- 在没有jsonp的情况下从另一个域获取数据(json格式)
- 使用 JSONP 调用的跨域 AJAX 返回纯 JSON
- Javascript CORS JSON/JSONP Request
- 如何在 cakephp 中回复 jsonp,而无需求助于 .json
- 使用 jQuery 和 jsonp (vimeo api) 按键获取选定的 json 值
- AngularJS在从HTTP返回的JSON中获取语法错误.JSONP.
- 数据类型 jsonp 和 JSON 之间的区别
- 为什么 $.getJson 不能与 json 或 jsonp 一起使用
- RESTful JSON 端点应该以 .js 结尾吗?JSONP呢?
- 使用 ajax 将 Json/Jsonp 数据放入表单中
- 无法使用 JSONP 访问 json 页面
- 使用 Ajax 调用 Deezer API (jquery) - dataType JSON 返回空 - JSONP 返
- 尝试使用 WOT API 从 JSON 或 JSONP 中提取数据
- 用于 json 和 jsonp 的 $.ajax 和 $.getJSON 无法正确获取来自第三方服务器的响应
- JQuery-对没有JSONP的JSON文件的跨域Ajax调用
- 如何拉动&显示JSON/JSONP文件中的数据
- jQuery.ajax返回jsonp而不是json