-1

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"
  }

]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
akhinair
  • 73
  • 1
  • 7
  • The OP already tagged the question with [tag:jq]. – John Kugelman Apr 19 '22 at 20:40
  • 1
    What specific technical problem did you encounter that stopped you from doing this on your own? – Charles Duffy Apr 19 '22 at 20:48
  • (did you already know how to do it with one element but have a problem that only came up when trying to add multiple elements? If so, show what you already had, and show that problem -- that way you disambiguate the question from existing append-to-an-array-with-jq questions, of which there are many). – Charles Duffy Apr 19 '22 at 20:49

1 Answers1

0

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
ikegami
  • 367,544
  • 15
  • 269
  • 518