Issue
I am having the below json array and i wanted to append two additional key value pairs in the json array using bash. This is need to add dynamically on my existing json array file. Can somebody share some ideas on fixing this?
json array file :
[
{
"entry": "10.20.15.0/24",
"comment": "test ip1"
},
{
"entry": "10.20.16.0/24",
"comment": "test ip2"
}
]
additional key value pair I wanted to append,
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
so the final json array should look like as below,
[
{
"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"
}
]
Solution
Hardcoded records to add:
jq '
. + [
{
"entry": "10.20.17.0/24",
"comment": "test ip3"
},
{
"entry": "10.20.18.0/24",
"comment": "test ip4"
}
]
' file.json
Records to add provided as an argument:
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
Records to add provided as a file:
jq --argfile to_add to_add.json '. + $to_add' file.json
or
jq --slurp add file.json to_add.json
Answered By - ikegami Answer Checked By - Candace Johnson (WPSolving Volunteer)