首页 > 解决方案 > Convert stdout to JSON

问题描述

How to grep the wanted text and receive it into stdout as JSON, i hope that someone can answer that , the result i get in the server API is text with. But I want the result to be in JSON {}, so I can loop through it in front-end. This is my back-end requests

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

This is the code that runs in 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",
        ""
    ] }

标签: node.jsjsonbash

解决方案


按行拆分输出。

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


推荐阅读