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