Bash script that convert any output (text) to json form

free -k | { read 
    read TITLE TOTAL USED REST
    echo "{\"Memory\":\"$(( 100 * $USED / $TOTAL ))\"}"
}

The output of free is piped to a compound command consisting of:
A first "read" which skips the first output line of "free".
A second "read" which reads the line we need, we need only the second and third value.
An echo which prints the line in the format you want including the calculation


Here's an example for memory:

echo {\"Memory\":\"$(awk '/^Mem/ {printf("%u", 100*$3/$2);}' <(free -m))\"} > mem.json

Putting that new file name into json:

echo {\"file\":\"$(ls mem.json)\"} > filename.json

Or:

echo {\"<paramName-here>\":\"$(<value-of-param-from-command-here>)\"} > mem.json 

When it gets more complicated than this, you can continue to write line by line or more likely build strings in a variable.


I created a tool called jc that converts the output of many command line tools, inclduing free to json:

$ jc free | jq
[
  {
    "type": "Mem",
    "total": 3993360,
    "used": 293248,
    "free": 3185992,
    "shared": 1196,
    "buff_cache": 514120,
    "available": 3465280
  },
  {
    "type": "Swap",
    "total": 2097148,
    "used": 0,
    "free": 2097148
  }
]

https://github.com/kellyjonbrazil/jc