windows 上的js gurus,
我通过shelljs发送一些curl请求并返回一些JSON。
示例JS-Code
var sh = require('shelljs');
sh.exec('curl -H "Accept: application/vnd.github.v3.text-match+json" \\ ' +
'https://api.github.com/repos/jquery/jquery/tags ',
{silent:true}).output;
现在,我想用jsawk解析JSON。我的想法与Bash shell extract object from json file和How to parse json with shell scripting类似。
我的问题是如何在node_modules文件夹structur(也许是.bin文件夹)中安装jsawk并在sh.exec
上作为附加语句运行?
有人有想法吗?
另一种方式可能是grep
和awk
JSON数据。我想查看name
属性,找到正确的版本号(例如2.1.1)并致电zipball_url
。但我不应该通过shell基础知识做到这一点。
Best,Ronn
答案 0 :(得分:0)
只需使用npm:
npm install jsawk
它在node_modules中自动安装jsawk,然后你可以在你的脚本中使用它:
var jsawk = require('jsawk');
但是你为什么要使用shell中的curl,有更好的方法来获取http数据,基本就是http请求
var https = require('https');
var options = {
host: 'api.github.com',
path: '/repos/jquery/jquery/tags',
port: 443,
method: 'GET',
headers: {'User-Agent': 'nodejstestagent'}
};
var req = https.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
var jsonResponse = JSON.parse( body) ;
console.log( JSON.stringify( jsonResponse,null,3 ));
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
将输出如下内容:
[
{
"name": "2.1.1-rc2",
"zipball_url": "https://api.github.com/repos/jquery/jquery/zipball/2.1.1-rc2",
"tarball_url": "https://api.github.com/repos/jquery/jquery/tarball/2.1.1-rc2",
"commit": {
"sha": "c2fdcaaacd4d7f8479b2196525330c1738e30cd3",
"url": "https://api.github.com/repos/jquery/jquery/commits/c2fdcaaacd4d7f8479b2196525330c1738e30cd3"
}
},
{
"name": "2.1.1-rc1",
"zipball_url": "https://api.github.com/repos/jquery/jquery/zipball/2.1.1-rc1",
"tarball_url": "https://api.github.com/repos/jquery/jquery/tarball/2.1.1-rc1",
"commit": {
"sha": "6ba4c8def1f9b0d03c5e8de1d64a78ae36646fb6",
"url": "https://api.github.com/repos/jquery/jquery/commits/6ba4c8def1f9b0d03c5e8de1d64a78ae36646fb6"
}
},
针对User-Agent的https和github规则进行了更新