Output JSON from Bash script

后端 未结 6 1343
暖寄归人
暖寄归人 2020-12-07 18:00

So I have a bash script which outputs details on servers. The problem is that I need the output to be JSON. What is the best way to go about this?

6条回答
  •  自闭症患者
    2020-12-07 18:04

    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

    And now I can easily execute it:

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

提交回复
热议问题