I have a bash array
X=(\"hello world\" \"goodnight moon\")
That I want to turn into a json array
[\"hello world\", \"goodni
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' ]