Output JSON from Bash script
If you only need to output a small JSON, use printf
:
printf '{"hostname":"%s","distro":"%s","uptime":"%s"}\n' "$hostname" "$distro" "$uptime"
Or if you need to produce a larger JSON, use a heredoc as explained by leandro-mora. If you use the here-doc solution, please be sure to upvote his answer:
cat <<EOF > /your/path/myjson.json{"id" : "$my_id"}EOF
Some of the more recent distros, have a file called: /etc/lsb-release
or similar name (cat /etc/*release
). Therefore, you could possibly do away with dependency your on 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.
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)donevars=(${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 ", " fidoneprintf "}"echo
And now I can easily execute it:
$ echo key1 1 key2 2 key3 3 | ./json.sh{"key1":1, "key2":2, "key3":3}