简体   繁体   English

将 bash output 转换为 JSON

[英]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.我似乎无法在我的 output 上加引号。

Use jq : 使用jq

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

The input is read as raw text, not JSON. 输入被读取为原始文本,而不是JSON。 Each line is split on a space (the argument to split may need to be adjusted depending on the actual input). 每行在一个空格上splitsplit参数可能需要根据实际输入进行调整)。 jq ensures that values are properly quoted when constructing the output objects. jq确保在构造输出对象时正确引用值。

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). 不要这样做:而是使用@ chepner's answer ,它保证生成具有所有可能输入的有效JSON作为输出(或者,如果没有JSON表示形式,则以非零退出状态失败)。

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). 以下只进行测试,以与该问题所示的特定输入有效的JSON,并会相当肯定产生的输出, 是不是与许多可能的输入(与文字引号中的字符串,在文字反斜杠结尾的字符串,等等),有效的JSON。

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

For JSON conversion of common shell commands, a good option is jc (JSON Convert)对于普通shell命令的JSON转换, jc(JSON Convert)是一个不错的选择

There is no parser for clustat yet though.不过,目前还没有clustat的解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM