How to format a bash array as a JSON array

后端 未结 5 934
醉酒成梦
醉酒成梦 2021-01-02 05:02

I have a bash array

X=(\"hello world\" \"goodnight moon\")

That I want to turn into a json array

[\"hello world\", \"goodni         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 05:28

    This ...

    X=("hello world" "goodnight moon" 'say "boo"' 'foo\bar')
    
    json_array() {
      echo -n '['
      while [ $# -gt 0 ]; do
        x=${1//\\/\\\\}
        echo -n \"${x//\"/\\\"}\"
        [ $# -gt 1 ] && echo -n ', '
        shift
      done
      echo ']'
    }
    
    json_array "${X[@]}"
    

    ... yields:

    ["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"]
    

    If you are planning to do a lot of this (as your reluctance to use a subshell suggests) then something such as this that does not rely on any subprocess is likely to your advantage.

提交回复
热议问题