JQ: remove nested key and keep other main array key intact

Viewed 669

I have a json file looking like this:

{
  "parents": [{
    // array of objects
  }],
  "modules": {
    "a": 1,
    "b": 2
  }
}

I want to remove they key b of the object modules.

I am running this command: jq "with_entries(.value |= del(.b))"

But this fails when the parents array is present. I get

Cannot index array with string "b"

How can I make the command ignore the parents array and only work on the modules object?

1 Answers

Your idea was right, but you missed the selecting the object desired inside with_entries(), hence your delete operation was attempted on all the objects in your JSON.

Since the parents record is an array type and not an object , the del function throws out an error that its not able to index the array with the given name. You need to do

with_entries( select(.key == "modules").value |= del(.b) )

The select() function filters that object keyed by name "modules" and applies the delete action on that object alone.

jq-play snippet

Related