user3595231
user3595231

Reputation: 765

how to replace only one key/value pair by using jq in json file?

My json template is as of this:

{ 
  "interface_settings": [
    {
      "name": "lan", 
      "status": "$status", 
      ...
    },
    {
     "name": "lte1",
     "status": "$status", 
     ...
    },
    { 
      ...
    }
  ],
  ...
}

And my jq command:

jq '.interface_settings[].status="up"' <my_json_template file> 

will update both status values within the interface_settings section. How may I just have one changed ?

Upvotes: 0

Views: 189

Answers (1)

peak
peak

Reputation: 116977

let's say I want to update the status where the name is "lan"

One way to update all such objects would be:

.interface_settings |= map( if .name == "lan" then .status = "up" else . end)

Just the first such

.interface_settings |= (reduce .[] as $x (null;
  if .done
  then .ans += [$x]
  elif $x.name == "lan"
  then .ans += [$x | .status = "up"] | .done = true
  else .ans += [$x]
  end) | .ans)

Upvotes: 1

Related Questions