给定一个 bash 数组,如何将其转换为 JSON 数组,以便使用 jq 输出到文件?
另外:有没有办法保持 server_nohup 数组不变,而不是每次都重写整个 json 文件?
newArray=(100 200 300)
jq -n --arg newArray $newArray '{
client_nohup: [
$newArray
],
server_nohup: [
]
}' > $projectDir/.watch.json
电流输出:
{
"client_nohup": [
"100"
],
"server_nohup": []
}
所需输出:
{
"client_nohup": [
100,
200,
300
],
"server_nohup": []
}
给定一个 bash 数组,如何将其转换为 JSON 数组
假设您的 jq 支持
--args
命令行选项,
您可以将它与内置 $ARGS
伪变量结合使用,如以下示例所示:
$ declare -a output=($'abc\ndef' "x y z")
$ jq -c -n '$ARGS.positional' --args "${output[@]}"
["abc\ndef","x y z"]
这里,bash数组的所有值都被转换为JSON字符串。请注意,bash 数组的第一个值中嵌入的换行符已正确处理。
另外...
(1) 如果 newArray 中的所有值都作为不带空格的 JSON 值有效,那么您可以将这些值作为流传输,例如
newArray=(100 200 300)
echo "${newArray[@]}" |
jq -s '{client_nohup: ., server_nohup: []}'
(2) 现在假设您只想更新文件中的“nohup”对象,例如 nohup.json:
{ "client_nohup": [], "server_nohup": [ "keep me" ] }
既然你使用的是bash,那么你可以这样写:
echo "${newArray[@]}" |
jq -s --argjson nohup "$(cat nohup.json)" '
. as $newArray | $nohup | .client_nohup = $newArray
'
(1)
{
"client_nohup": [
100,
200,
300
],
"server_nohup": []
}
(2)
{
"client_nohup": [
100,
200,
300
],
"server_nohup": [
"keep me"
]
}
有志者事竟成:-)
例如,请参阅How to format a bash array as a JSON array(尽管这不是一个完全通用的解决方案)中接受的答案。
您可能希望将数字字符串转换为 JSON 数字,例如使用 jq 习语:
(tonumber? // .)
。
您可能还希望利用 bash 字符串不能包含 NUL 字符这一事实。
一般来说,唯一真正安全的方法是多次调用
jq
,将每个元素添加到上一个命令的输出中。
arr='[]' # Empty JSON array
for x in "${newArray[@]}"; do
arr=$(jq -n --arg x "$x" --argjson arr "$arr" '$arr + [$x]')
done
这可确保
x
数组的每个元素 bash
在添加到 JSON 数组之前都已正确编码。
但这很复杂,因为
bash
并不区分数字和字符串。这会将您的数组编码为 ["100", "200", "300"]
,而不是 [100, 200, 300]
。最后,您需要了解数组包含的内容,并相应地对其进行预处理。