h.b
h.b

Reputation: 349

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.

Upvotes: 3

Views: 14382

Answers (3)

eddygeek
eddygeek

Reputation: 4500

For JSON conversion of common shell commands, a good option is jc (JSON Convert)

There is no parser for clustat yet though.

clustat output does look table-like, so you may be able to use the --asciitable parser with jc.

Upvotes: 2

Charles Duffy
Charles Duffy

Reputation: 295443

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"\"}"
       }' 

Upvotes: 2

chepner
chepner

Reputation: 531175

Use jq:

sudo clustat | grep primary |
  jq -R 'split(" ")|{service:.[0], server:.[1], status:.[2]}'

The input is read as raw text, not JSON. Each line is split on a space (the argument to split may need to be adjusted depending on the actual input). jq ensures that values are properly quoted when constructing the output objects.

Upvotes: 8

Related Questions