Home > Mobile >  How to parse and convert string list to JSON string array in shell command?
How to parse and convert string list to JSON string array in shell command?

Time:02-10

How to parse and convert string list to JSON string array in shell command?

'["test1","test2","test3"]'

to

test1
test2
test3

I tried like below:

string=$1
array=${string#"["}
array=${array%"]"}

IFS=',' read -a array <<< $array; 

echo "${array[@]}"

Any other optimized way?

CodePudding user response:

eval "array=($( jq -r 'map( @sh ) | join(" ")' <<<"$json" ))"

CodePudding user response:

As bash and jq are tagged, this solution relies on both (without summoning eval). The input string is expected to be in $string, the output array is generated into ${array[@]}. It is robust wrt spaces, newlines, quotes, etc. as it uses NUL as delimiter.

mapfile -d '' array < <(jq -j '.[]   "\u0000"' <<< "$string")
Testing
string='["has spaces\tand tabs","has a\nnewline","has \"quotes\""]'
mapfile -d '' array < <(jq -j '.[]   "\u0000"' <<< "$string")
printf '==>%s<==\n' "${array[@]}"
==>has spaces   and tabs<==
==>has a
newline<==
==>has "quotes"<==
  • Related