Alex
Alex

Reputation: 2805

Delete key/value pair with jq when key is a known string

I'm trying to delete one specific key/value pair from a json file.

My json file is, for this example, params.json

[ 
 {
    "ParameterKey": "RTSMMinSize",
    "ParameterValue": "1"
  },
  {
    "ParameterKey": "RTSMReplicateDB",
    "ParameterValue": "false"
  },
  {
    "ParameterKey": "RTSMSnapshotID",
    "ParameterValue": "snapID"
  },
  {
    "ParameterKey": "RTSMEMAIL",
    "ParameterValue": ""
  }
]

I want to remove the RTSMSnapshotID key value pair entirely as part of my bash script. The file should look like this after:

[ 
 {
    "ParameterKey": "RTSMMinSize",
    "ParameterValue": "1"
  },
  {
    "ParameterKey": "RTSMReplicateDB",
    "ParameterValue": "false"
  },
  {
    "ParameterKey": "RTSMEMAIL",
    "ParameterValue": ""
  }
]

I thought this would be something as simple as

jq 'del(.RTSMSnapshotID)' params.json  

but I'm getting

jq: error (at <filename>): Cannot index array with string "RTSMSnapshotID"

Clearly I don't understand how delete works. Any help?

Upvotes: 3

Views: 1670

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295679

del(.foo) expects there to be a top-level dictionary with a key named foo. That's not the case here; instead, you have a top-level list with ParameterKey having a series of values, with only one of which you want to remove the entire pair.

jq '[ .[] | select(.ParameterKey != "RTSMSnapshotID") ]'

...or...

jq 'map(select(.ParameterKey != "RTSMSnapshotID"))'

Upvotes: 6

Related Questions