willemdh
willemdh

Reputation: 856

How to convert string list to JSON string array in Bash?

How can I convert a variable in Bash with a string list containing newlines, like this

groups="group_1
group_2
group_3"

to a JSON string array:

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

Is this possible with jq?

Upvotes: 11

Views: 14255

Answers (1)

peak
peak

Reputation: 116870

If your jq has inputs then the simplest would probably be to use it:

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

Otherwise, here are three alternatives:

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))'

In any case, the array can easily be incorporated into a JSON object, e.g. by extending the filter with | {groups: .}

If you really want to produce invalid JSON, consider:

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

Output:

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

Note on select(length>0)

Consider:

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

The reason for including select(length>0) is to avoid the trailing "".

If $groups contains consecutive newlines, and if it is important to retain the empty strings, then you might want to use [:-1], e.g.

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

If your jq does not support [:-1], make the 0 explicit: [0:-1]

Upvotes: 24

Related Questions