Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

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

Writer Matthew Barrera

I want to create bash script that it converts output of other scripts (Normally simple text) in a valid json form. How can I do this ?

Example:

awk '/^Mem/ {printf("%u%%", 100*$3/$2);}' <(free -m)

command give me used memory. I want to get output in valid jason form.

Desired output:

 {“Memory”:”80”}
0

3 Answers

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

5

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 }
]

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy