javascript - javascript/node.js 中的 JSONP 解析
问题描述
例如,如果我有一个包含 JSONP 响应的字符串"jsonp([1,2,3])"
,并且我想检索第三个参数3
,我该如何编写一个函数来为我做这件事?我想避免使用eval
. 我的代码(如下)在调试行上运行良好,但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
更多信息:我正在使用request
库在 node.js 刮板中运行它。
这是一个 jsfiddle https://jsfiddle.net/bortao/3nc967wd/
解决方案
只需slice
删除jsonp(
and的字符串);
,然后您就可以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
请注意,这new Function
与eval
.
推荐阅读
- python - 在 CentOS 上安装 python3
- python - 在python中,如何检查与一组值相关的不确定性是否正态分布?
- vba - 使用文件和缩略图填充列表视图表单
- python-3.x - ImportError:.Elf 文件中没有名为“PyQt4”的模块
- flask - flask_wtf.file 中的 FileField 不是 werkzeug.datastructures.FileStorage 的实例
- typescript - 打字稿在返回嵌套对象时不返回嵌套类型
- html - 如何在 100vh 页面上禁用移动设备上的垂直滚动?
- excel - 使用 VBA 将多个单元格粘贴到一个单元格中
- amazon-web-services - AWS S3 放置事件 Lambda 创建具有正确所有者 Cognito 的 DynamoDB 条目
- php - PHP 未捕获的 com_exception:参数 0:类型不匹配