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?
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"] }
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]
[:-1] serves to suppress reporting the trailing \n as an additional array element is surprising, given that even without it, interior lines are reported without their trailing \n, and, curiously, [:-1] doesn't trim an additional character from the end. Generally, split() employs separator logic rather than terminator logic.jq question, I'd recommend using printf '%s' "$groups" instead of echo -n; then you can use the shorter jq filter with any shell without worrying about how echo will interpret the-n "option".