Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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”}
share|improve this question
    
This is not off-topic. –  chaskes Nov 2 '13 at 3:05
add comment

2 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

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 question...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 parser...in that case he would have asked so. –  thom Nov 2 '13 at 2:31
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

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.