50

所以我有一个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

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

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

谢谢。

4

7 回答 7

96

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

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

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

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

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

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

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

于 2012-09-21T05:00:26.653 回答
56

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

cat <<EOF > /your/path/myjson.json
{"id" : "$my_id"}
EOF
于 2015-10-19T19:53:08.737 回答
3

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

First of all, I created a bash script called 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}
于 2016-05-02T07:16:31.490 回答
1

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

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"  }
    ]
}
于 2017-11-17T08:30:23.033 回答
1

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

$ ./getDistro.sh | json_encode
["my.dev","Ubuntu 17.10","4 days, 2 hours, 21 minutes, 17 seconds"]
于 2018-02-16T11:13:34.920 回答
0
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"
于 2019-09-03T19:56:59.870 回答
0

To answer the subject line, if you were to needing to to get a tab separated output from any command line and needed it to be formatted as a JSON list of lists, you can do the following:

echo <tsv_string> | python3 -c "import sys,json; print(json.dumps([row.split('\t') for row in sys.stdin.read().splitlines() if True]))

For example, to get a zfs list output as json:

zfs list -Hpr -o name,creation,mountpoint,mounted | python3 -c "import sys,json; print(json.dumps([row.split('\t') for row in sys.stdin.read().splitlines() if True]))
于 2020-12-30T17:53:27.183 回答