Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ?


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:

share|improve this question
free -k | { read 
    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

share|improve this answer
That's a totally non-portable method, how could I go if I want to add more complex JSON objects? – Braiam Nov 2 '13 at 1:58
I might have misunderstood you wanted the percentage of free memory in JSON form isn't it ? If not, please explain in more detail what you expect. – thom Nov 2 '13 at 2:14
"I want to create bash script that it converts output of other scripts (Normally simple text) in a valid json form." The memory was just an example. With your approach he would need to write a method for each input. – Braiam Nov 2 '13 at 2:17
That is not enough info. You understand of course that the format of the input must be given. Are we talking about something simple like key value pairs for example ? Is there a way the OP can narrow it down a bit ? The question is too fuzzy. – thom Nov 2 '13 at 2:25
Of course I don't expect that the OP asks for a full blown that case he would have asked so. – thom Nov 2 '13 at 2:31

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


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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.