如何在Bash中将字符串列表转换为JSON字符串数组? [英] How to convert string list to JSON string array in Bash?
问题描述
如何在Bash中使用包含换行符的字符串列表转换变量,像这样
How can I convert a variable in Bash with a string list containing newlines, like this
groups="group_1
group_2
group_3"
到JSON字符串数组:
to a JSON string array:
{
[ "group_1", "group_2", "group 3" ]
}
jq有可能吗?
推荐答案
如果您的jq具有inputs
,那么最简单的方法就是使用它:
If your jq has inputs
then the simplest would probably be to use it:
jq -ncR '[inputs]' <<< "$groups"
["group1","group2","group3"]
否则,这是三种选择:
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))'
在任何情况下,该数组都可以轻松地合并到JSON对象中,例如通过使用| {groups: .}
In any case, the array can easily be incorporated into a JSON object, e.g. by extending the filter with | {groups: .}
如果您真的想产生无效的JSON,请考虑:
If you really want to produce invalid JSON, consider:
printf "%s" "$groups" | jq -Rrsc 'split("\n") | "{ \(.) }"'
输出:
{ ["group_1","group_2","group_3"] }
关于select(length> 0)
的说明考虑:
Note on select(length>0)
Consider:
jq -Rsc 'split("\n")' <<< $'a\nb'
["a","b",""]
包含select(length>0)
的原因是为了避免在结尾加上".
The reason for including select(length>0)
is to avoid the trailing "".
如果$ groups包含连续的换行符,并且保留空字符串很重要,那么您可能要使用[:-1]
,例如
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"]
如果您的jq不支持[:-1]
,请明确指定0:[0:-1]
If your jq does not support [:-1]
, make the 0 explicit: [0:-1]
这篇关于如何在Bash中将字符串列表转换为JSON字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!