在bash中动态添加json数组中的多个键值对



我有下面的json数组,我想使用bash在json数组中附加两个额外的键值对。这需要在我现有的json数组文件上动态添加。有人能分享一些关于解决这个问题的想法吗?

数组文件:

[
{
"entry": "10.20.15.0/24",
"comment": "test ip1"
},
{
"entry": "10.20.16.0/24",
"comment": "test ip2"
}
]

附加的键值对,

{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}

那么最终的json数组应该如下所示,

[
{
"entry": "10.20.15.0/24",
"comment": "test ip1"
},
{
"entry": "10.20.16.0/24",
"comment": "test ip2"
},
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]

要添加的硬编码记录:

jq '
. + [
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]
' file.json

要添加的记录作为参数提供:

jq --argjson to_add '
[
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]
' '. + $to_add' file.json

要添加的记录以文件形式提供:

jq --argfile to_add to_add.json '. + $to_add' file.json

jq --slurp add file.json to_add.json

最新更新