将标准输出转换为JSON。

4
如何使用grep将所需文本作为JSON输出到stdout,我希望有人能够回答这个问题。服务器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",
        ""
    ] }

我已经修改了代码,如果你运行它,stdout会给你free -m,但是以文本形式,那么我怎样才能在json {}中获取stdout呢? - The pyramid
1个回答

2

将输出按行分割。

res.json({'results': stdout.split('\n')}) - 现在你可以循环遍历 results

PS: 最后的换行符可以被删除,因为它是空的。这是脚本完成后的新行。

UPDATE

请查看下面的函数,并像这样使用它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));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接