h.b h.b - 2 months ago 6
JSON Question

Convert bash output to JSON

I am running the following command:

sudo clustat | grep primary | awk 'NF{print $1",""server:"$2 ",""status:"$3}'


Results are:

service:servicename,server:servername,status:started
service:servicename,server:servername,status:started
service:servicename,server:servername,status:started
service:servicename,server:servername,status:started
service:servicename,server:servername,status:started


My desired result is:

{"service":"servicename","server":"servername","status":"started"}
{"service":"servicename","server":"servername","status":"started"}
{"service":"servicename","server":"servername","status":"started"}
{"service":"servicename","server":"servername","status":"started"}
{"service":"servicename","server":"servername","status":"started"}


I can't seem to put the qoutation marks withour srewing up my output.

Answer

Don't do this: Instead, use @chepner's answer, which is guaranteed to generate valid JSON as output with all possible inputs (or fail with a nonzero exit status if no JSON representation is possible).

The below is only tested to generate valid JSON with the specific inputs shown in the question, and will quite certainly generate output that is not valid JSON with numerous possible inputs (strings with literal quotes, strings ending in literal backslashes, etc).

sudo clustat |
  awk '/primary/ {
         print "{\"service\":\"" $1 "\",\"server\":\"" $2 "\",\"status\":\""$3"\"}"
       }' 
Comments