文件內容以下json
[root@Master opt]# cat /opt/json.txt aa bb cc
腳本內容以下bash
[root@Master opt]# cat json.sh #!/bin/bash #array=(aa bb cc) array=($(cat /opt/json.txt)) printf "{\n" printf '\t"data":[\n' for ((i=0;i<${#array[@]};i++)) do printf '\t\t{\n' num=$(echo $((${#array[@]}-1))) if [ "$i" == ${num} ]; then printf "\t\t\t\"{#DISK_NAME}\":\"${array[$i]}\"}\n" else printf "\t\t\t\"{#DISK_NAME}\":\"${array[$i]}\"},\n" fi done printf "\t]\n" printf "}\n"
執行腳本輸出json格式ide
[root@Master opt]# sh json.sh { "data":[ { "{#DISK_NAME}":"aa"}, { "{#DISK_NAME}":"bb"}, { "{#DISK_NAME}":"cc"} ] }