node.js - 将标准输出转换为 JSON

标签 node.js json bash

如何 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

thanks for https://stackoverflow.com/users/2076949/darklightcode i can split the results but can i get inside the array the results like this

 { results : [ { "total" : the total number, "free" : the free number, "etc" : "etc" } ] } 

not like this

{
    "results": [
        "              total        used        free      shared  buff/cache   available",
        "Mem:            992         221         235          16         534         590",
        "Swap:           263         245          18",
        ""
    ] }

最佳答案

按行拆分输出。

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));

关于node.js - 将标准输出转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772516/

相关文章:

node.js - 我可以使用 require 获取 createSagaMiddleware 吗?

c# - 将 JSON 作为 .json 文件返回

javascript - 我可以通过 <b> 标签过滤返回的 JSON 吗?

javascript - OpenAI GPT-3 API 错误 : "This model' s maximum context length is 2049 tokens"

linux - 在 linux 屏幕中保留我的环境

mysql - 第 1 行 : Column cannot be null 处的错误 1048 (23000)

node.js - 为什么在单独的模型文件中使用 model.export?

angularjs - Visual Studio 2015 无法识别 Ionic 和 angularjs 参数

git - 当存在 var_dump 时中止 git pre-commit 钩子(Hook)

node.js - Node JS、Highcharts 内存使用率不断攀升