How to format a bash array as a JSON array

后端 未结 5 955
醉酒成梦
醉酒成梦 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:31

    If the values do not contain ASCII control characters, which have to be escaped in strings in valid JSON, you can also use sed:

    $ X=("hello world" "goodnight moon")
    $ printf %s\\n "${X[@]}"|sed 's/["\]/\\&/g;s/.*/"&"/;1s/^/[/;$s/$/]/;$!s/$/,/'
    ["hello world",
    "goodnight moon"]
    

    If the values contain ASCII control characters, you can do something like this:

    X=($'a\ta' $'a\n\\\"')
    for((i=0;i<${#X[@]};i++));do
      [ $i = 0 ]&&printf \[
      printf \"
      e=${X[i]}
      e=${e//\\/\\\\}
      e=${e//\"/\\\"}
      for((j=0;j<${#e};j++));do
        c=${e:j:1}
        if [[ $c = [[:cntrl:]] ]];then
          printf '\\u%04x' "'$c"
        else
          printf %s "$c"
        fi
      done
      printf \"
      if((i<=${#X[@]}-2));then
        printf ,
      else
        printf \]
      fi
    done
    

提交回复
热议问题