从 Bash 脚本输出 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12524437/
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-03 18:32:56  来源:igfitidea点击:

Output JSON from Bash script

jsonbash

提问by Justin

So I have a bashscript which outputs details on servers. The problem is that I need the output to be JSON. What is the best way to go about this? Here is the bash script:

所以我有一个bash脚本可以输出服务器的详细信息。问题是我需要输出为JSON. 解决这个问题的最佳方法是什么?这是 bash 脚本:

# Get hostname
hostname=`hostname -A` 2> /dev/null

# Get distro
distro=`python -c 'import platform ; print platform.linux_distribution()[0] + " " +        platform.linux_distribution()[1]'` 2> /dev/null

# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
uptime="$days days, $hours hours, $minutes minutes, $seconds seconds"
else
uptime=""
fi

echo $hostname
echo $distro
echo $uptime

So the output I want is something like:

所以我想要的输出是这样的:

{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}

Thanks.

谢谢。

回答by Steve

If you only need to output a small JSON, use printf:

如果您只需要输出一个小的 JSON,请使用printf

printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"

Or if you need to produce a larger JSON, use a heredocas explained by leandro-mora. If you use the here-doc solution, please be sure to upvote his answer:

或者,如果您需要生成更大的 JSON,请使用Leedro-mora解释的heredoc。如果您使用 here-doc 解决方案,请务必支持他的回答

cat <<EOF > /your/path/myjson.json
{"id" : "$my_id"}
EOF


Some of the more recent distros, have a file called: /etc/lsb-releaseor similar name (cat /etc/*release). Therefore, you could possiblydo away with dependency your on Python:

一些较新的发行版有一个名为:/etc/lsb-release或类似名称 ( cat /etc/*release) 的文件。因此,你可以有可能废除Python的依赖你:

distro=$(awk -F= 'END { print  }' /etc/lsb-release)

An aside, you should probably do away with using backticks. They're a bit old fashioned.

顺便说一句,您可能应该取消使用反引号。它们有点老式。

回答by Leandro Mora

I find it much more easy to create the json using cat:

我发现使用cat以下方法创建 json 更容易:

cat <<EOF > /your/path/myjson.json
{"id" : "$my_id"}
EOF

回答by Jimilian

I'm not a bash-ninja at all, but I wrote a solution, that works perfectly for me. So, I decided to share itwith community.

我根本不是 bash-ninja,但我写了一个解决方案,这对我来说非常有效。所以,我决定与社区分享

First of all, I created a bash script called json.sh

首先,我创建了一个名为的 bash 脚本 json.sh

arr=();

while read x y; 
do 
    arr=("${arr[@]}" $x $y)
done

vars=(${arr[@]})
len=${#arr[@]}

printf "{"
for (( i=0; i<len; i+=2 ))
do
    printf "\"${vars[i]}\": ${vars[i+1]}"
    if [ $i -lt $((len-2)) ] ; then
        printf ", "
    fi
done
printf "}"
echo

And now I can easily execute it:

现在我可以轻松地执行它:

$ echo key1 1 key2 2 key3 3 | ./json.sh
{"key1":1, "key2":2, "key3":3}

回答by Daro

@Jimilian script was very helpful for me. I changed it a bit to send data to zabbix auto discovery

@Jimilia 脚本对我很有帮助。我稍微改变了一下,将数据发送到zabbix 自动发现

arr=()

while read x y;
do
    arr=("${arr[@]}" $x $y)
done

vars=(${arr[@]})
len=${#arr[@]}

printf "{\n"
printf "\t"data":[\n"

for (( i=0; i<len; i+=2 ))
do
     printf "\t{  "{#VAL1}":\"${vars[i]}\",\t"{#VAL2}":\"${vars[i+1]}\"  }"

    if [ $i -lt $((len-2)) ] ; then
        printf ",\n"
    fi
done
printf "\n"
printf "\t]\n"
printf "}\n"
echo

Output:

输出:

    $ echo "A 1 B 2 C 3 D 4 E 5" | ./testjson.sh
{
    data:[
    {  {#VAL1}:"A", {#VAL2}:"1"  },
    {  {#VAL1}:"B", {#VAL2}:"2"  },
    {  {#VAL1}:"C", {#VAL2}:"3"  },
    {  {#VAL1}:"D", {#VAL2}:"4"  },
    {  {#VAL1}:"E", {#VAL2}:"5"  }
    ]
}

回答by Fedir RYKHTIK

I wrote a tiny program in Go, json_encode. It works pretty good for such cases:

我用 Go 写了一个小程序json_encode。对于这种情况,它非常有效:

$ ./getDistro.sh | json_encode
["my.dev","Ubuntu 17.10","4 days, 2 hours, 21 minutes, 17 seconds"]

回答by Navaganesh R

data=$(echo  " BUILD_NUMBER : ${BUILD_NUMBER} , BUILD_ID : ${BUILD_ID} , JOB_NAME : ${JOB_NAME} " | sed 's/ /"/g')

output => data="BUILD_NUMBER":"29","BUILD_ID":"29","JOB_NAME":"OSM_LOG_ANA"