将bash数组转换为json数组并使用jq插入文件 [英] Convert bash array to json array and insert to file using jq
问题描述
给出一个bash数组,如何将其转换为JSON数组以便使用jq输出到文件?
Given a bash array, how to convert it to a JSON array in order to output to a file with jq?
另外:是否有一种方法可以使server_nohup数组保持不变,而不是每次都重写整个json文件?
Additionnally: is there a way to keep the server_nohup array unchanged instead of re-writing the whole json file each time?
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": []
}
推荐答案
(1)如果newArray中的所有值都是有效的JSON值且没有空格,那么您就可以将这些值作为流进行管道传输,例如>
(1) If all the values in newArray are valid as JSON values without spaces, then you could get away with piping the values as a stream, e.g.
newArray=(100 200 300)
echo "${newArray[@]}" |
jq -s '{client_nohup: ., server_nohup: []}'
(2) 现在,假设您只希望更新文件中的"nohup"对象,例如nohup.json:
(2) Now let's suppose you merely wish to update the "nohup" object in a file, say nohup.json:
{ "client_nohup": [], "server_nohup": [ "keep me" ] }
由于您正在使用bash,因此可以编写:
Since you are using bash, you can then write:
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"
]
}
其他情况
有志者事竟成,:-)
Other cases
Where there's a will, there's a jq way :-)
例如,在>如何将bash数组格式化为JSON数组(尽管这不是一个完全通用的解决方案).
See for example the accepted answer at How to format a bash array as a JSON array (though this is not a completely generic solution).
这篇关于将bash数组转换为json数组并使用jq插入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!