簡體   English   中英

從 Bash 腳本輸出 JSON

[英]Output JSON from 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

所以我想要的輸出是這樣的:

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

謝謝。

如果您只需要輸出一個小的 JSON,請使用printf

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

或者,如果您需要生成更大的 JSON,請使用Leedro-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)

順便說一句,您可能應該取消使用反引號。 它們有點老式。

我發現使用cat創建 json 更容易:

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

我根本不是 bash-ninja,但我寫了一個解決方案,這對我來說非常有效。 所以,我決定與社區分享

首先,我創建了一個名為json.sh的 bash 腳本

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

現在我可以輕松地執行它:

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

@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

輸出:

    $ 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"  }
    ]
}

我用 Go 寫了一個小程序json_encode 對於這種情況,它非常有效:

$ ./getDistro.sh | json_encode
["my.dev","Ubuntu 17.10","4 days, 2 hours, 21 minutes, 17 seconds"]
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"

我創建了一個名為jc的工具,該工具可以將許多工具的輸出轉換,包括將uptime為json:

$ uptime | jc --uptime -p
{
  "time": "16:52",
  "uptime": "3 days, 4:49",
  "users": "5",
  "load_1m": "1.85",
  "load_5m": "1.90",
  "load_15m": "1.91"
}```

https://github.com/kellyjonbrazil/jc

要回答主題行,如果您需要從任何命令行獲取制表符分隔的輸出並需要將其格式化為 JSON 列表列表,您可以執行以下操作:

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

例如,要獲得一個 zfs 列表輸出為 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]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM