How can I convert a list of strings to an array of JSON strings in Bash?

How to convert a variable in Bash with a string list containing newlines like

groups="group_1
group_2
group_3"

      

to an array of JSON strings:

{
    [ "group_1", "group_2", "group 3" ]
}

      

Is this possible with jq?

+3


source to share


1 answer


If your jq has inputs

, then the easiest is to use it:

jq -ncR '[inputs]' <<< "$groups"
["group1","group2","group3"]

      

Otherwise, here are three options:

jq -c -n --arg groups "$groups" '$groups | split("\n")' 

echo -n "$groups" | jq -cRs 'split("\n")'

echo "$groups" | jq -R -s -c 'split("\n") | map(select(length>0))'

      

Either way, the array can be easily included in a JSON object eg. by extending the filter with| {groups: .}

If you really want to create invalid JSON, consider:

printf "%s" "$groups" | jq -Rrsc 'split("\n") | "{ \(.) }"'

      

Output:



{ ["group_1","group_2","group_3"] }

      

Optional note (length> 0)

Consider:

 jq -Rsc 'split("\n")' <<< $'a\nb'
 ["a","b",""]

      

The reason for including select(length>0)

is to avoid lagging "".

If $ group contains consecutive newlines and if it is important to keep blank lines, you can use [:-1]

eg.

jq -cRs 'split("\n")[:-1]' <<< "$groups"
["group1","group2","group3"]

      

If your jq doesn't support [:-1]

, make 0 explicit:[0:-1]

+5


source







All Articles