如何将bash数组格式化为JSON数组
问题描述:
我有一个bash数组
X=("hello world" "goodnight moon")
我想变成一个json数组
That I want to turn into a json array
["hello world", "goodnight moon"]
是否有一种好方法可以将其转换为json字符串数组,而无需遍历子shell中的键?
Is there a good way for me to turn this into a json array of strings without looping over the keys in a subshell?
(for x in "${X[@]}"; do; echo $x | sed 's|.*|"&"|'; done) | jq -s '.'
这显然行不通
echo "${X[@]}" | jq -s -R '.'
答
您可以执行以下操作:
X=("hello world" "goodnight moon")
printf '%s\n' "${X[@]}" | jq -R . | jq -s .
输出
[
"hello world",
"goodnight moon"
]