从Bash脚本输出JSON

Jus*_*tin 42 bash json

所以我有一个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
Run Code Online (Sandbox Code Playgroud)

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

{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ste*_*eve 76

使用以下echo命令替换脚本末尾的三个命令:

echo -e "{\"hostname\":\""$hostname"\", \"distro\":\""$distro"\", \"uptime\":\""$uptime"\"}"
Run Code Online (Sandbox Code Playgroud)

-e用于解释反斜杠转义

或者用这个:

printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"
Run Code Online (Sandbox Code Playgroud)

一些最近的发行版,有一个名为:/etc/lsb-release或类似名称(cat /etc/*release)的文件.因此,您可能取消对Python的依赖:

distro=$(awk -F= 'END { print $2 }' /etc/lsb-release)
Run Code Online (Sandbox Code Playgroud)

除此之外,你应该放弃使用反引号.他们有点老式.

  • `printf`会更清洁:`printf'{"hostname":"%s","distro":"%s","uptime":"%s"} \n'"$ hostname""$ distro ""正常运行时间"` (16认同)

小智 46

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

cat <<EOF > /your/path/myjson.json
{"id" : "$my_id"}
EOF
Run Code Online (Sandbox Code Playgroud)

  • 仅当不需要JSON编码时,这才是完整的解决方案。 (3认同)