将 bash 输出转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39707264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:14:03  来源:igfitidea点击:

Convert bash output to JSON

jsonbashawksed

提问by h.b

I am running the following command:

我正在运行以下命令:

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

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.

我似乎无法在不增加输出的情况下加上引号。

回答by chepner

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. Each line is split on a space (the argument to splitmay need to be adjusted depending on the actual input). jqensures that values are properly quoted when constructing the output objects.

输入被读取为原始文本,而不是 JSON。每行在一个空格上分开(split可能需要根据实际输入调整参数)。jq确保在构造输出对象时正确引用值。

回答by Charles Duffy

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 notvalid JSON with numerous possible inputs (strings with literal quotes, strings ending in literal backslashes, etc).

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

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