How to format a bash array as a JSON array

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

    If you're OK with a few extra backslashes, bash's printf "%q" is useful:

    X=("hello world" "goodnight moon" 'say "boo"' 'foo\bar')
    json="[$(printf '"%q",' "${X[@]}")"
    json="${json%,}]"
    echo "$json"
    
    ["hello\ world","goodnight\ moon","say\ \"boo\"","foo\\bar"]
    

    Regarding the OK-ness of the backslashes: node.js doesn't have a problem with them:

    $ node
    > x = ["hello\ world","goodnight\ moon","say\ \"boo\"","foo\\bar"]
    [ 'hello world',
      'goodnight moon',
      'say "boo"',
      'foo\\bar' ]
    

提交回复
热议问题