如何grep所需的文本并将其接收为标准输出 JSON,我希望有人能回答这个问题,我在服务器API中得到的结果就是文本。但是我希望结果在JSON {}中,所以我可以在前端循环遍历它。这是我的后端请求
var express = require('express');
var exec = require("child_process").exec;
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || xxxx;
app.get('/', function(req, res) {
res.json('API is Online!');
});
app.post('/data', function(req, res){
//executes my shell script - test.sh when a request is posted to the server
exec('sh test.sh' , function (err, stdout, stderr) {
if (!err) {
res.json({'results': stdout})
}
});
})
app.listen(port);
console.log('Listening on port ' + port);
这是在bash中运行的代码
#!/bin/bash
free -m
感谢https://stackoverflow.com/users/2076949/darklightcode 我可以拆分结果,但可以在数组内部获得这样的结果
{ results : [ { "total" : the total number, "free" : the free number, "etc" : "etc" } ] }
不喜欢
{
"results": [
" total used free shared buff/cache available",
"Mem: 992 221 235 16 534 590",
"Swap: 263 245 18",
""
] }
答案 0 :(得分:1)
按行分割输出。
res.json({'results': stdout.split('\n')})
-现在您可以遍历results
。
PS:可以删除最后一个换行符,因为它是空的。脚本完成后,这是新行。
更新
请参见下面的功能,并像convertFreeMemory(stdout.split('\n'))
一样使用它
console.clear();
let data = {
"results": [
" total used free shared buff/cache available",
"Mem: 992 221 235 16 534 590",
"Swap: 263 245 18",
""
]
};
convertFreeMemory = (input) => {
let objectFormat = [];
input = input
.filter(i => i.length)
.map((i, idx) => {
i = i.split(' ').filter(x => x.length);
if (idx !== 0) {
i.splice(0, 1);
}
return i;
});
let [header, ...data] = input;
for (let idx = 0; idx < data.length; idx++) {
let newObj = {};
for (let index = 0; index < header.length; index++) {
if (typeof newObj[header[index]] === 'undefined') {
newObj[header[index]] = '';
}
let value = data[idx][index];
newObj[header[index]] = typeof value === 'undefined' ? '' : value;
}
objectFormat.push(newObj);
}
return objectFormat;
}
console.log(convertFreeMemory(data.results));