Search code examples
jsonshellselectkeyjq

identify an item in json and update key and value in it


my input json is given below , i want select if "Name": "bot-block" then update it's ​"Action": to "Block": {} from "Allow": {},i performed this this using select command but it filters my json and only returns the item with .Name=bot-block,i want updation in json not filtering .this is my current command jq '.[] | select(.Name=="bot-block") | .Action |= . + { "Block" : {} } ' input.json

   [
{
 "Name": "searchblock",
 "Priority": 3,
 "Action": {
   "Block": {}
 },
 "VisibilityConfig": {
   "SampledRequestsEnabled": true,
   "CloudWatchMetricsEnabled": true,
   "MetricName": "searchblock"
 }
},
{
 "Name": "bot-block",
 "Priority": 4,
 "Action": {
   "Allow": {}
 },
 "VisibilityConfig": {
   "SampledRequestsEnabled": true,
   "CloudWatchMetricsEnabled": true,
   "MetricName": "user-agent"
 }
}
]

expected output

    [
{
  "Name": "searchblock",
  "Priority": 3,
  "Action": {
    "Block": {}
  },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "searchblock"
  }
},
{
  "Name": "bot-block",
  "Priority": 4,
  "Action": {
    "Block": {}
  },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "user-agent"
  }
}
]


Solution

  • You can directly "assign" to the Action element of the selected array item. |= only affects the selected item, but the output of the filter is still the entire input.

    jq  'map(select(.Name=="bot-block").Action |= {Block: {}})' input.json